Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File is not written on disk until program ends

Tags:

c

unix

I'm writing a file using a c code on a unix system . I open it , write a few lines and close it. Then i call a shell script, say code B where this file is to be used and then return back to main program. However, when code B tries to read the file, the file is empty.

I checked the file on the file system, its size is shown as 0 and no data is present in file. However after killing the running c code process, file has data present in it.

Here is the piece of code -

void writefile(){
  FILE *fp;
  fp = fopen("ABC.txt","w");
  fputs("Some lines...\n",fp);
  fclose(fp);

  system("code_B ABC.txt");
}

Please advise how can I read the file in the shell script without stopping the c code process.

like image 225
abhisahay Avatar asked Feb 13 '26 08:02

abhisahay


2 Answers

If there's some time between the fputs and fclose, add

fflush(fp);

This will cause the contents of the disk file to be written.

like image 53
Mark Harrison Avatar answered Feb 15 '26 22:02

Mark Harrison


You should do fsync() after the fclose(), to guarantee the writing of the file to the disk.

Take a look at this question:

Does Linux guarantee the contents of a file is flushed to disc after close()?

like image 45
miluz Avatar answered Feb 15 '26 22:02

miluz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!