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.