C语言~数据文件通过使用删除功能修改文本文件内容(文件IO)



我还是个新手,还在学习C语言。目前,我的代码有问题。任务是删除文件IO中的某些内容,默认情况下,我的txt文件中有一些记录。该任务要求用户在txt文件中输入他/她想要删除的行。然而,问题出现了:

1(c程序在第一次仍能工作,但第二次、第三次及以下的程序无法工作。(这意味着可以在第一时间删除行(

我认为这是一个缓冲区问题,所以我添加了许多fflush代码,但仍然无法解决。

2( 我想将我的程序更改为使用关键字来查找记录并删除。用户键入记录号可以删除整个项目记录。然而,我不知道它是如何工作的。

如果有人能帮助我,我非常感激和高兴。1( 代码如下:

#include<stdio.h> #include<stdlib.h>      
int main(){
FILE *fileptr1, *fileptr2, *fileptr3;
char filename[40]="itemrecord.txt";
char save;
int delete_line, temp = 1;
char reply;
printf("Enter file name: ");
scanf("%s", filename);
do{

//open file in read mode
fileptr1 = fopen(filename, "r");
if (fileptr1== NULL){
printf("open unsuccessful,file not exist"); 
exit(1);
}
save = getc(fileptr1);
while (save != EOF)
{
printf("%c", save);
save = getc(fileptr1);
}
//rewind
rewind(fileptr1);
fflush(stdout);
printf(" nn Enter line number of the line to be deleted <type 0 = not 
delete anything>:");
fflush(stdin);
scanf("%d", &delete_line);

//open new file in write mode
fileptr2 = fopen("copy.c", "w");
save = 'a';
while (save != EOF)
{
save = getc(fileptr1);
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(save, fileptr2);
}
if (save == 'n')
{
temp++;
}
}
fclose(fileptr1);
fclose(fileptr2);
remove(filename);
//rename the file replica.c to original name
rename("copy.c", filename);
fflush(stdout);
printf("nThe contents of file after being changed are as follows:n");
fileptr1 = fopen(filename, "r");
save = getc(fileptr1);
while (save != EOF)
{
printf("%c", save);
save = getc(fileptr1);
}
fflush(stdout);
fflush(stdin);
fclose(fileptr1); 
printf("nn Delete anther item?<y/n>: ");
scanf("%c",&reply);  
}while(reply=='y' || reply=='Y');
return 0;
}

结果:

Enter file name:itemrecord
mary 1 123
sam  2 124
bob  3 125
Enter line number of the line to be deleted<type 0=not delete anything>:1
The contents of file after being changed are as follows:
sam  2 124
bob  3 125
Delete other record?<y/n>:y
sam  2 124
bob  3 125
Enter line number of the line to be deleted<type 0=not delete anything>:1
The contents of file after being changed are as follows:
sam  2 124
bob  3 125   
Delete other record?<y/n>:n
//second time doesn't work.//

很抱歉代码太长,问题太长,但我太困惑了。。。

2( 如果我的记录进入

Mary
1
123
sam  
2 
124
bob  
3 
125

那么我怎样才能键入"玛丽"删除整个记录项目呢?类似的。。。

sam  
2 
124
bob  
3 
125

试试这个

int delete_line, temp;
char reply;
printf("Enter file name: ");
scanf("%s", filename);
do{
temp = 1;
....

我希望这能有所帮助。