I have this code below
#include <stdio.h>
int main(){
int i=0;
for(i=0; i<1000; i++) {
int count2 = 2;
test_val(count2);
sleep(1);
printf("zzz..\n");
}
return 1;
}
int test_val(count)
{
FILE *p;
p = fopen("test.txt", "ab");
if(p == NULL)
{
printf("Unable to open file!");
return 0;
}
fprintf(p, "count is %d\n", count);
return 1;
}
I compiled this function with name “test”
Where with this function, it will print 2 until 1000 times. It will put everything in test.txt if this function is run correctly. But if I in the middle of iteration (let’s say I have already run 500 iterations)
I run kill-9 test (or ctrl+c), it will kill the program.
I thought at first I will get at least in test.txt 500 times “count is 2” printed there (until I send a kill signal), but in fact, it does not. It works if I wait until the program finishes and printing “count is 2 . What actually happen ?
I need to make a program that can cancel in the middle of iteration, and can still print until the latest iteration before kill execution in the text..
Thank you for any response
Thank you
stdioI/O functions are buffered, the C library keeps a buffer, and flushes it under certain circumstances. You can flush an output buffer explicitly usingfflush().fclose()does an implicit flush before closing a file.