4

I have an std::ifstream object:

std::ifstream file(file_path);

I read lines from it:

std::getline(file, line);

Is it legal to add lines to this file from another place while the stream is open? E.g. even after I reach EOF in the C++ program, can lines be added through a text editor, and getline be called again to get the newly added lines? What does the standard say?

DMH
  • 3,875
  • 2
  • 26
  • 25
tmppp
  • 195
  • 1
  • 6
  • This post seems relevant? http://stackoverflow.com/questions/15385302/reading-a-file-while-it-is-being-written-by-another-process – taocp Jun 14 '13 at 15:52
  • open system call may not succeed. what are you trying to do, if you want an app to write into a file, then another to read at the same time, try to used a pipe, search for "pipe c++" – aah134 Jun 14 '13 at 15:53
  • It is legal, but it's not likely to do what you want it to. You may get lucky, though... – twalberg Jun 14 '13 at 16:11
  • Go ahead and try for yourself ;) – Vivek Jain Jun 14 '13 at 16:19

1 Answers1

0

It is legal and it should do what you expect on most reasonable operating systems. Note that the input stream needs to be cleared in case you reach EOF. The output stream needs to be flushed one way or another. The code below illustrates that.

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    const char *f = "f.txt";
    // create an empty file
    std::ofstream os(f);
    os.close();
    std::ifstream is(f);
    for (unsigned i = 1; 3 > i; ++i)
    {
        os.open(f, std::ios_base::out | std::ios_base::app);
        os << "line  " << i << std::endl;
        os.close();
        std::string s;
        is.clear();
        std::getline(is, s);
        std::cerr << s << std::endl;
    }
    os.open(f, std::ios_base::out | std::ios_base::app);
    for (unsigned i = 3; 6 > i; ++i)
    {
        os << "line  " << i << std::endl;
        os.flush();
        std::string s;
        is.clear();
        std::getline(is, s);
        std::cerr << s << std::endl;
    }
}
Come Raczy
  • 1,590
  • 17
  • 26