简体   繁体   中英

How to write a text file by C++ continuously and read the same text file continuously by other program(not c++) at the same time?

I am using VC++ to generate a text file and write (via fstream) data continuously to it. I have another application2 (NOT C++) which accesses that same file which c++ appends. At the instant application2 accesses the file, new data from C++ program cannot be written to it. It seems like the new data from c++ goes to some temporary file. when application2 closes the file, new data gets updated to the file. I want the data to be written to the file in real time and be read at the same time by application2. What should I do in c++ to make new data appear in the file which is opened by application2?

C++ side:

int realTimeValues  // this variable is updated continuously

FILE * pFileTXT; 

while(1)
{
 pFileTXT = fopen ("realTimeData.txt","a"); // Opening file in append mode
 fprintf (pFileTXT, "%d\n",realTimeValues);   // saving values to file
 fclose (pFileTXT)                            // Closing the file
}

On the application2 side I can't tell how exactly its opening this file. The application is Universal Real-Time Software Oscilloscope. In the menu there is an option "read from a file"

Ugh. There are a number of things at work:

  1. By default, fprintf output may be buffered in a private ram buffer. This buffer is flushed only as needed or when you do fclose. If you want to force the data out, there's a setbuf call you can make (read the docs) or explicitly call fflush after each fprintf.
  2. I do not know if fopen allows for simultaneous readers. Probably not, given the buffering behavior. If you want read/write sharing, you should look at the documentation to see if there is an explicit mode parameter to enable this.
  3. Unfortunately, this only covers the part you can control. If the reader (an application you do not control) doesn't support shared reading, then you're out of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM