Why do the strings output using fprintf end up not being written to the output file if my program is terminated via CTRL-C? -


why fprintf give different results in following example programs?

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 terminate program using ctrl+c, 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 terminate program using ctrl+c, file named filename, , contains many lines string asdas.

why strings not written file in first example, written file in second example?

in second case, there enough fprintf calls internal buffers flushed disk.

with first program, if put fflush(f) before while loop, strings written file.

#include <stdio.h>  int main(void) {     file *f = fopen("filename", "w");     if (!f) {         perror("failed open 'filename' 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 x64 ... /out:file.exe                                                        c:\...\temp> file                             ^c                                                                  c:\...\temp> type filename                    asdas                                                               asdas

keep in mind:

upon successful completion, fflush() shall return 0; otherwise, shall set error indicator stream, return eof, , set errno indicate error.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -