如何在 c 中迭代地将文本附加到 .txt 文件

How to append text to a .txt file iteratively in c

我在用 C 语言迭代写入 .txt 文件时遇到困难。

我需要在 for 循环的每次迭代后写出一系列值,这样如果我在任何时候从 运行ning 停止我的程序,我都不会丢失我已经收集的数据。

如果我 运行 通过我的整个循环,我的代码可以工作,但是如果我使用 ctrl+c 命令停止来自 运行ning 的程序,因为它占用了我的 .txt 文件太长的时间是空的。

我不知道这是不是ctrl+c命令导致的,因为文件没有机会关闭,但有没有其他解决办法?我应该在每次循环迭代期间打开文件并关闭它并附加到 .txt 文件吗?我认为这可能会导致之前写入 .txt 文件的数据被覆盖,也会导致增加 运行 时间。

这是我目前正在做的一个非常简单的例子,希望它能说明我正在努力完成的事情:

FILE *fp;
fp = fopen("Output.txt", "w");
int a = 0;
int b = 0;
int c = 0;
for(int i=0;i<500;i++)
{
    a = a+1;
    b = b+1;
    c = c+1;
    printf("a = %d\tb = %d\tc = %d\n"); // printing to console
    fprintf(fp,"%d,%d,%d\n",a,b,c); // printing to file
}
fclose(fp);

您需要在每个 fprintf 文件后 fflush

If stream points to an output stream or an update stream in which the most recent operation was not input, fflush()shall cause any unwritten data for that stream to be written to the file, and the last data modification and last file status change timestamps of the underlying file shall be marked for update.

for(int i=0;i<500;i++)
{
    a = a+1;
    b = b+1;
    c = c+1;
    printf("a = %d\tb = %d\tc = %d\n"); // printing to console
    fprintf(fp,"%d,%d,%d\n",a,b,c); // printing to file
    fflush(fp); /* <== here */
}

PS: 空白不是稀缺商品。