Why are lines printed using fprintf not written to the output file if my program terminates with CTRL-C?

Why fprintf

does it give different results in the following program examples?

Example 1:

int main(){
    FILE *f;
    char buf[512];
    char name[128] = {"filename"};

    f = fopen(name, "w");
    fprintf(f, "asdas\n");
    fprintf(f, "asdas\n");
    while(1){}
    return 0;
}

      

If I terminate this program with CTRL+ C, I get an empty file named filename

.

However, using

Example 2:

int main(){
    FILE *f;
    char buf[512];
    char name[128] = {"wpa_supplicant.conf"};

    f = fopen(name,"w");
    while(1){
        fprintf(f, "asdas\n");
    }
    return 0;
}

      

If I terminate this program with CTRL+ C, I get a file named filename

and contains many lines with a string asdas

.

Why are the lines not written to the file in the first example, but they are written to the file in the second example?

+3


source to share


2 answers


In the second case, it suffices fprintf

to flush the internal buffers to disk.

In the first program, if you put fflush(f)

before the loop while

, the lines will be written to the file.

#include <stdio.h>

int main(void) {
    FILE *f = fopen("filename", "w");
    if (!f) {
        perror("Failed to open 'filename' for writing");
        exit(EXIT_FAILURE);
    }

    fprintf(f, "asdas\n");
    fprintf(f, "asdas\n");

    if ( fflush(f) != 0 ) {
        perror("Flushing output failed");
        exit(EXIT_FAILURE);
    }

    while(1){}
    return 0;
}

      

Output:



C: \ ... \ Temp> cl file.c                       
Microsoft (R) C / C ++ Optimizing Compiler Version 18.00.31101 for x64
...
/out:file.exe                                                      

C: \ ... \ Temp> file                            
^ C                                                                 
C: \ ... \ Temp> type filename                   
asdas                                                              
asdas

Keep in mind:

fflush()

Returns on successful completion 0

; otherwise, it should set an error indicator for the stream, return EOF

and set errno

to indicate an error.

+5


source


As @ SinanÜnür's answer mentioned , this is indeed a problem with buffering data in internal buffers. In the first case, you need to manually clear the data that will be written to the file.

However, FWIW, I just want to add here, you see this behavior due to an abnormal program termination by the signal (generated by the CTRL+ C).



If your program exited normally (for example, by calling exit()

after a sufficiently large but controlled loop while()

), both cases exhibited the same behavior as in this scenario, all open streams would be automatically cleaned up.

The function exit()

should then flush all open streams with unwritten buffered data and close all open streams. Finally, the process must be completed ...

+1


source







All Articles