Why does it only print after I finish the program?

Viewed 47

While the program is running, when I enter 1, nothing is printed to the result.txt file, but after the program is completed, everything is printed in the file, why does this happen? And how can I make it print while the program is running, thank you so much!

Here is my code

#include <stdio.h>

void print_to_file(FILE *f);

int main()
{
    FILE *f;
    f = fopen("result.txt", "r+");
    int choice;
    while (1)
    {
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            print_to_file(f);
            break;
        }
        if (choice == 2)
            break;
    }
    fclose(f);
    return 0;
}

void print_to_file(FILE *f)
{
    int k = 2;
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            fprintf(f, "%d ", k);
            k += 2;
        }
        fprintf(f, "\n");
    }
}

PS: I use the switch statement because there are other cases that I want the program to do later.

1 Answers

Stream output functions such as printf are fully buffered by default when writing to a file. The contents will be flushed automatically when the file is closed with fclose(f). You can manually flush the buffer using fflush(f).

Related