我有一个旨在管理txt文件中学生记录的程序。我试图删除学生记录。程序打开文件,读取内容并打印出来供用户查看。然后,用户输入要删除的行的整数。然后它返回新内容供用户查看。
int deleteStudent()
{
FILE *dOldFile, *dNewFile;//Original file and New temp file
char ch;
int deleteLine, temp = 1;
dOldFile = fopen(fName, "r");//fName is name of file user enters in previous function
ch = getc(dOldFile);
while (ch != EOF)
{
printf("%c", ch);//Prints content of Original file for user to see
ch = getc(dOldFile);
}
rewind(dOldFile);
printf(" \n Enter line number of the line to be deleted:\n>");
scanf("%d", &deleteLine);//user selects which line of file to be removed
dNewFile = fopen("copy.c", "w");
ch = getc(dOldFile);
while (ch != EOF)
{
ch = getc(dOldFile);
if (ch == '\n')
temp++;
if (temp != deleteLine) //except the line to be deleted
{
putc(ch, dNewFile); //copy all lines in file copy.c
}
}
fclose(dOldFile);
fclose(dNewFile);
remove(fName);
rename("copy.c", fName);
printf("\n Student Records Remaining:\n");
dOldFile = fopen(fName, "r");
ch = getc(dOldFile);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(dOldFile);
}
fclose(dOldFile);
printf("\n");
return 0;
}
问题是,我相信这可能是我的while循环的一个问题,是从 fprintf 打印到新的和重命名的文本文件的内容删除了第一个字符,从我的内容理解,在编辑结束时打印的EOF符号。例如,原始文件有
23 John Smith 18 5555555
24 Tom Costa 15 5555555
25 Barry West 35 5555555
26 Daren carr 22 5555555
例如,如果用户决定删除第3行。这是txt文件中的结果
3 John Smith 18 5555555
24 Tom Costa 15 5555555
26 Daren carr225555555ÿ
答案 0 :(得分:2)
每件事都很好。只需用while循环替换while循环并删除
ch = getc(dOldFile);
之前如图所示:
dNewFile = fopen("copy.c", "w");
//ch = getc(dOldFile); comment this out
while((ch = getc(dOldFile))!=EOF)
{
if (ch == '\n')
temp++;
if (temp != deleteLine) //except the line to be deleted
{
putc(ch, dNewFile); //copy all lines in file copy.c
}
} //modify while to make it better
fclose(dOldFile);
fclose(dNewFile);