为什么文件只包含第一次迭代的打印

Why the file contains only the print from first iteration

我用 C 语言编写了这段代码,在 txt 文件中一个一个地打印 1 到 10 的编号,但在执行后,只有第一个 no 被打印在 txt 文件中。请帮忙

 #include<stdio.h>
 #include<stdlib.h>
 int main()
 {
     int i;
     FILE *fptr;

     fptr=fopen("C:\program.txt","w");

     for(i=1;i<=10;i++)
     {
         fprintf(fptr,"\n%d\n",i);
         fclose(fptr);
     }
 }

您需要将 fclose() 放在 for 循环体之后。

否则,您将在第一次迭代后关闭文件指针,并且涉及指针的所有连续循环都将调用 undefined behaviour,因为您将使用 invalid 文件指针(已经关闭)。

在完成写入文件之前不要关闭文件。

#include<stdio.h>
#include<stdlib.h>
int main()
{

    int i;

    FILE *fptr;
    fptr=fopen("C:\program.txt","w");


    for(i=1;i<=10;i++)
    {


        fprintf(fptr,"\n%d\n",i);
    }
    fclose(fptr);

}

循环的第一次迭代后,您使用 fclose 关闭文件描述符。将其移出其下方的循环。

正如man fclose所说:

[...] any further access (including another call to fclose()) to the stream results in undefined behavior.


备注:

  • 您应该检查 fopen
  • 的 return 值