Search code examples
creal-timefopenprintf

Write file in real time with C


How may I write data into a file in real time? I mean: A program gets data and puts them into a file (we can say out.txt) with a fprintf(...) command, then another program read data from the file (out.txt) and elaborates them.

I have a flow like this:

fp=fopen("out.txt","w+");

    while(...) {

    ...

    fprintf (fp,"\n %s", data);

}

fclose(fp);

With that flow I get data into the file (out.txt) after I have closed the file.

Is there a way to write data in real time into the file?


Solution

  • I suspect you mean simultaneously when you say in real time. Simultaneous access to a file requires to open a shared file. This may be a pipe or some other interprocess communication. It may also be a simple file on disk, as asked for. Windows allows to open a shared file by means of _fsopen.

    #include <share.h> // required for manifest constants for shflag parameter.
    
    fp = _fsopen("out.txt","w+",_SH_DENYWR); // e.g. _SH_DENYWR denies write access
       .
    while(...) {
       .
       .
    

    Another process can read the file while it is open; no need to close the file beforehand. The other process may even write (with shflag = _SH_DENYNO). However, writing and reading simultaneously from different processes requires some more coding effort.

       .
      fprintf (fp,"%s\n", data); // you may want to have the /n "new line" after writing the data
       .
    

    Not all the written content is always immedeately written to the file (physically). Therefore it is required to force the content to be writen to the file after the fprintf.

       .
      fflush(fp); // force writing to device    
       .
    }