我是新手,还在学习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(" \n\n 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("\n\n 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
那么我如何输入“Mary”删除整个记录项?类似的东西...
sam
2
124
bob
3
125
最佳答案
试试这个
int delete_line, temp;
char reply;
printf("Enter file name: ");
scanf("%s", filename);
do{
temp = 1;
....
希望对您有所帮助。
关于C语言~数据文件利用delete函数修改文本文件内容(File IO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53430909/