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

时间:2018-11-22 12:20:52

标签: c file file-io text-files

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

1)c程序仍然可以在第一次运行,但是第二,第三次及以后不能运行(这意味着可以在第一次删除行)

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

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

如果有人可以帮助我,我将非常感激和高兴。  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'delele整个记录项?那样的东西...

sam  
2 
124

bob  
3 
125

1 个答案:

答案 0 :(得分:0)

尝试一下

int delete_line, temp;
char reply;

printf("Enter file name: ");
scanf("%s", filename);

do{
    temp = 1;
    ....

我希望这会有所帮助。