我正在为一本简单的电话簿编写代码。一切正常,除了使用我的删除功能成功删除条目后,我的追加功能似乎不再写入文件的条目了。除非我删除了我用来存储条目的database.data文件。
注意: 字符数组文件=" 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");
}
结构条目 {
char fn[15]; char ln[15]; char mn[15]; char bd[9]; char cn[11]; }p;
如果您想了解更多详情,请告诉我。
UPDATE -
我将问题缩小到删除函数中的while循环,如果while循环中的内容是这样写的话,我的append函数似乎在使用delete后工作:
while (ch!=EOF) { ch=getc(filepointer); if(count!=tode) { fprintf(filepointer2,"%c",ch); if(ch=='\n') { count++; } } }
但是如果以这种方式编写while循环,它将删除指定行之后的所有条目。而在我之前的删除函数中的while循环代码中,它只删除了该特定行,但如上所述,追加函数无法写入文件的问题将持续存在,直到我删除文件"数据库。数据"手动
答案 0 :(得分:0)
解决问题的结果是append函数能够将条目写入文件唯一的问题是我的print函数无法打印出新条目,因为delete函数在执行后留下了垃圾。修改了代码,以便在删除后不会写入垃圾。
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!!");
}