C程序不写入文本文件

C program not writing to text file

问题来了:

我想将一些文本写入 文本文件,但我遇到了一些奇怪的情况:

样本 1:

int main()
{
    FILE *file = fopen("structures.txt", "a+"); // open the file for reading & writing
    int choice = 0;

    if(file == NULL)
        puts("Unable to open text file");
    else { 
        do {
            scanf("%d", &choice);
            fprintf(file, "This is testing for fprintf...\n");
        }while(choice > 0);
    }
    fclose(file);

    return 0;
}

在此版本的程序中,没有任何内容写入文本文件,我不明白为什么。但对我来说最奇怪的是接下来:

样本 2:

int main()
{
    FILE *file = fopen("structures.txt", "a+"); // open the file for reading & writing
    int choice = 0;

    if(file == NULL)
        puts("Unable to open text file");
    else { 
        do {
            scanf("%d", &choice);
            fprintf(file, "This is testing for fprintf...\n");
            fclose(file); // Added this line, the writing works
        }while(choice > 0);
    }
    fclose(file);

    return 0;
}

fprintf调用后直接添加fclose(file);后,程序成功写入:

This is testing for fprintf...

到文本文件。

我的问题是:

Does that mean that I have to open my text file whenever I want to write some text to it & close it directly afterwards ?

不,但这可能意味着您需要先关闭文件,然后您写入的内容才会被刷新并写入文件。

Does fclose() has anything to do with the writing process ?

大多数文件流都经过缓冲。这意味着每次写入都会进入内存。它不会写入磁盘,直到缓冲区已满或您调用关闭。

What are the factors that prevent fprintf() from working ? (1st sample)

任何明显错误的地方。

How can I open & close the text file just ONCE, at the start of the program & at the end of it (respectively) guaranteeing at the same time that my program will work flawlessly ?

你可以这样调用 fflush()。但是你确定你试过这个并且文件在你最后关闭文件后什么都不包含吗?

我使用 int fflush (FILE *stream) 解决了这个问题(@Jonathan 暗示过)。

Flushing output on a buffered stream means transmitting all accumulated characters to the file. There are many circumstances when buffered output on a stream is flushed automatically:

When you try to do output and the output buffer is full.

When the stream is closed.

When the program terminates by calling exit.

When a newline is written, if the stream is line buffered.

Whenever an input operation on any stream actually reads data from its file.

所以基本上,我只需要在调用 fprintf() 之后调用 fflush() :

fprintf(file, "This is testing for fprintf...\n");
fflush(file);