案例2是有问题的部分。最后,它应该删除文件" List.txt"并重命名文件" newlist.txt"到" List.txt"但这些都不会发生,并且两个函数都返回-1,因此两个文件在执行后都保留在目录中。
#include <stdio.h>
#include <string.h>
int main()
{
char menu, firstName[20], lastName[30], stdNum[10], avgInt[3], avgDec[3];
do
{
FILE *listPtr;
printf("Menu: \n1 : Add a new student\n2 : Remove a student\n3 : Edit a student\n4 : Search a student\n5 : Sort the students\n6 : Exit\n\n");
menu = getch();
if(menu != 6)
switch(menu)
{
case '1':
{
listPtr = fopen("List.txt", "a");
//first name
printf("Enter the first name:\n");
scanf("%19s", firstName);
fprintf(listPtr, firstName);
fputc(' ', listPtr);
//last name
printf("\nEnter the last name:\n");
scanf("%29s", lastName);
fprintf(listPtr, lastName);
fputc(' ', listPtr);
//student number
printf("\nEnter the student number:\n");
scanf("%9s", stdNum);
fprintf(listPtr, stdNum);
fputc(' ', listPtr);
//average
printf("\nEnter the student's average score:\n");
printf("Integer part:");
scanf("%s", avgInt);
fprintf(listPtr, avgInt);
fputc(' ', listPtr);
printf("Decimal part:");
scanf("%s", avgDec);
fprintf(listPtr, avgDec);
fputc('\n', listPtr);
fclose(listPtr);
break;
}
case '2':
{
listPtr = fopen ("List.txt", "r");
if(feof(listPtr))
printf("You haven't saved any students yet.");
else
{
int found = 0;
listPtr = fopen("list.txt", "r");
printf("Enter the student's student number:");
char tempNum[10];
scanf("%s", tempNum);
do
{
fscanf(listPtr, "%s %s %s %s %s", firstName, lastName, stdNum, avgInt,avgDec);
if(strcmp(tempNum, stdNum) == 0)
{
found = 1;
break;
}
} while(strcmp(tempNum, stdNum) != 0 && !feof(listPtr));
if(found == 0)
printf("This student doesn't exist in the list.");
else
{
rewind(listPtr);
FILE *tempList;
tempList = fopen("newlist.txt", "w");
while(!feof(listPtr))
{
fscanf(listPtr, "%s %s %s %s %s", firstName, lastName, stdNum, avgInt, avgDec);
if(strcmp(tempNum, stdNum) != 0 && !feof(listPtr))
fprintf(tempList, "%s %s %s %s %s\n", firstName, lastName, stdNum, avgInt, avgDec);
}
fclose(listPtr);
fclose(tempList);
remove("List.txt");
rename("newlist.txt", "List.txt");
}
}
break;
}
case '3':
break;
case '4':
break;
case '5':
break;
}
} while(menu != '6');
}