c code: fprintf print on file less times than expected

I ran 10 copy of the same code (changing only some parameters) simultaneously in 10 different folder (each program working in single core).
In each program I have a for loop (the number of iterations, NumSamples, can be 50000, 500000 or 5000000 (the number of iteration depend on the specific time of execution of a single iteration; A greater number of iteration are performed in quicker cases )). Inside each iteration I compute a certain quantity (a double variable) and then save it on file with (inside the for block):
fprintf(fp_TreeEv, "%f\n", TreeEv);
where TreeEv is the name of the variable computed at each cycle.
To be sure that the code save the variable right after the fprintf command I set the buffer to 0 after the file opening, with:

TreeEv=fopen("data.txt", "a");
setbuf(TreeEv, NULL);
The program ends without error. Also I know that all the NumSamples iterations have been done during the execution (I print a variable initialized with 0 at the beginning of the for loop and that increase by one at each cycle).
When I open the txt file, at the ending of code execution I see that inside the file there are less row (data) than expected (NumSamples), for example 4996187 instead of 5000000
What could be the source of the problem?

I copy below the for loop of my code(inv_trasf is just a function that generate random numbers):\

    char NomeFiletxt [64];
    char NomeFilecsv [64];
    sprintf(NomeFilecsv, "TreeEV%d.csv", N);
    sprintf(NomeFiletxt, "TreeEVCol%d.txt", N);
    FILE* fp_TreeEv;
    fp_TreeEv=fopen(NomeFilecsv, "a");
    FILE* fp_TreeEvCol;
    fp_TreeEvCol=fopen(NomeFiletxt, "a");
    setbuf(fp_TreeEv, NULL);
    setbuf(fp_TreeEvCol, NULL);

    for(ciclo=0; ciclo<NumSamples; ciclo++){

        sum = 0;
        for(i=0; i<N; i++){

                k_max_int = deg_seq[i];


        TreeEV = ((double)sum_2/sum)-1.;
        fprintf(fp_TreeEv, "%f,", TreeEV);
        fprintf(fp_TreeEvCol, "%f\n", TreeEV);

    CycleCount +=1;

Could the problem stay in the null buffer?
Only codes with greater execution time (on the single cycle iteration) save correctly all the expected data. From man setbuf "If the argument buf is NULL, only the mode is affected; a new buffer will be allocated on the next read or write operation."

Read more here: https://stackoverflow.com/questions/66305027/c-code-fprintf-print-on-file-less-times-than-expected

Content Attribution

This content was originally published by user1172131 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: