我喜欢 Ben Russels 的回答。这是我的版本,以避免在 c 代码中重复最后一行。它有效,但我不明白为什么,因为 if (fgets != NULL)
它应该做这个工作的条件。
int main ()
{
FILE* pFile;
char name[41] = "fileText04.txt";
char text[81];
int i;
pFile = fopen("fileText04.txt", "wt");
if (pFile == NULL)
{
printf("Error creating file \n");
exit(1);
}
else
{
for (i=0; i<5; i++)
{
printf("Write a text: \n");
fgets(text, 81, stdin);
fputs(text, pFile);
}
}
fclose (pFile);
pFile = fopen(name, "rt");
if (pFile == NULL)
{
printf("File not found. \n");
exit(2);
}
while (! feof(pFile))
{
fgets(text, 80, pFile);
if (feof(pFile)) // This condition is needed to avoid repeating last line.
break; // This condition is needed to avoid repeating last line.
if (fgets != NULL)
fputs(text, stdout);
}
fclose (pFile);
return 0;
}
非常感谢,杰米·戴维