gpt4 book ai didi

c - 为什么我的追加函数不再写入文件

转载 作者:行者123 更新时间:2023-11-30 17:25:38 25 4
gpt4 key购买 nike

我正在为一个简单的电话簿编写代码。一切正常,除了使用删除函数成功删除条目后,我的附加函数似乎无法再将条目写入文件。除非我删除用于存储条目的database.data 文件。

注意:字符数组 file="database.data"

删除功能:

void deletee()
{


int tode,count;
char ch;
printc();
count=1;

FILE *filepointer,*filepointer2;

filepointer=fopen(file,"r+");
filepointer2=fopen("datatemp.data","w+");
if(filepointer==NULL)
{
printf("ERROR ERROR!");
}

printf("Enter line number of the line to be deleted: \n");
scanf("%d",&tode);
while (ch!=EOF)
{
ch=getc(filepointer);
if(ch=='\n')
{
count++;
}
if(count!=tode)
{
fprintf(filepointer2,"%c",ch);
}
}
fclose(filepointer);
fclose(filepointer2);
remove(file);
rename("datatemp.data",file);
printf("Content successfully deleted!!");

}

这是附加函数:

void append(struct entry *ptr)
{

FILE *filepointer;

filepointer=fopen(file,"a+");

fflush(stdin); //This block is asking for the inputs to be placed into the file
printf("Enter FName: ");
scanf("%s",&ptr->fn);
printf("\nEnter LName: ");
scanf("%s",&ptr->ln);
printf("\nEnter MName: ");
scanf("%s",&ptr->mn);
printf("\nEnter BD: ");
scanf("%s",&ptr->bd);
printf("\nEnter CNum: ");
scanf("%s",&ptr->cn);

if(filepointer==NULL)
{
printf("The file does not exist.\n");
return;
}

system("cls");
fprintf(filepointer,"%15s%15s%15s%9s%11s\n",ptr->fn,ptr->ln,ptr->mn,ptr->bd,ptr->cn);
fclose(filepointer);
printf("Entries successfully written!\n");
}

struct entry {

  char fn[15];
char ln[15];
char mn[15];
char bd[9];
char cn[11];
}p;

如果您想了解更多详细信息,请告诉我。

更新-

我将问题范围缩小到删除函数中的 while 循环,如果 while 循环中的内容写成这样,我的附加函数似乎在使用删除后可以工作:

    while (ch!=EOF)
{
ch=getc(filepointer);
if(count!=tode)
{
fprintf(filepointer2,"%c",ch);
if(ch=='\n')
{
count++;
}
}
}

但是如果 while 循环以这种方式编写,它将删除指定行后面的所有条目。而在我之前的 deletee 函数中 while 循环的代码中,它仅删除该特定行,但如上所述,附加函数无法写入文件的问题将持续存在,直到我手动删除文件“database.data” .

最佳答案

解决了问题,结果是追加函数能够将条目写入文件,唯一的问题是我的打印函数无法打印出新条目,因为删除函数在执行后留下了垃圾。修改了代码,删除后不会写入垃圾。

void deletee()

{

    int tode,count;
char ch,sc;
printc();
count=1;

FILE *filepointer,*filepointer2;

filepointer=fopen(file,"r+");
filepointer2=fopen("datatemp.data","w+");
if(filepointer==NULL)
{
printf("ERROR ERROR!");
}
printf("Enter line number of the line to be deleted: \n");
scanf("%d",&tode);
while (ch!=EOF)
{
ch=getc(filepointer);
if(count!=tode)
{
if(ch==EOF)
{
break;
}
fprintf(filepointer2,"%c",ch);

}
if(ch=='\n')
{
count++;
}

}
fclose(filepointer);
fclose(filepointer2);
swap();
remove("datatemp.data");
printf("Content successfully deleted!!");

}

关于c - 为什么我的追加函数不再写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27019556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com