1

If I have a program in c or c++ that writes to a particular text file and a program that reads from that same text file Is it possible for me to use the two programs simultaneously so that as the first program writes new data to the text file the other program can read it and detect the changes?

Any help would be appreciated.

Dappa jack
  • 145
  • 1
  • 2
  • 12
  • 4
    Use a pipe instead of a file for inter-process communication – StoryTeller - Unslander Monica Feb 23 '17 at 10:51
  • Yes, that's why you able to open one text file in multiple text editor simultaneously. – someone_ smiley Feb 23 '17 at 10:51
  • 4
    @someone_smiley: No, it's not. That's not how text editors work. – Lightness Races in Orbit Feb 23 '17 at 10:52
  • Simultaneously, not really, but you can lock the file (or parts of it) and wait in the other program until the lock is freed, and read it. Take a look [here](http://stackoverflow.com/questions/853805/locking-files-using-c-on-windows) for an example on Windows and C++. – Steeve Feb 23 '17 at 11:00
  • Yes, it's possible. It's also quite difficult to do reliably as various caching effects in both processes and in both file data and metadata can make detecting newly-written data difficult. Read this [IBM Redbook](http://www.redbooks.ibm.com/redpapers/pdfs/redp3945.pdf) and search for "read-behind-write". – Andrew Henle Feb 23 '17 at 11:02
  • Yes, it's possible - it's what the `tail -f` command does. –  Feb 23 '17 at 11:13
  • You may want to consider something like Berkeley sockets or [ZeroMQ](http://zeromq.org/). – pattivacek Feb 23 '17 at 14:19
  • The details can vary by operating system and whether you read and write using traditional I/O command or memory mapped files. – Adrian McCarthy Feb 24 '17 at 17:30

1 Answers1

1

Writing to a file:

if(fp)
{
    // fp -> handle to the file
    fputs("Satya Pawan Kartik", fp);
    fclose(fp);
}

Reading from the file:

for(;;)
{
    // fp -> handle to the file
    while(fgets(line, sizeof line, fp))
    {
        printf("%s\n", line);
    }
}

Let's say that the program writing to the text file is called write and the program reading the file is called read.

read obviously runs forever. Executing write displays the changes made by it to the text file by read. If required write can be modified to run forever and display the line written by it through a for loop counter. The same changes will be evidently visible in read.

So yes it is possible to write and read with 2 programs simultaneously.