Search code examples
c++stdfstreamifstreamofstream

Is file ready to read immediately after std::ofstream is destroyed?


Basically I have following workflow (through console application):

  • Read binary file (std::ifstream::read)
  • Do something with data read
  • Write back to same file (std::ofstream::write), overwriting what was there before.

Now, if I run this whole console program 1000 times through a shell script (always using same file), is it safe to assume that read operation will not conflict with previously run program trying to write to file? Or I need to wait between executions (how long???)? Can I reliably determine if file is ready?

I know it is not the best design, just want to know if that will work reliably (trying to quickly gather some statistics - inputs are different, but output file is always same - needs to be read, info needs to be processed, then it needs to be updated (at this point simply overwriting it) ).

EDIT:

It looks like the problem with output being wrong is not related to OS based on answers, the read/write I do looks like:

//read
    std::ifstream input(fname,std::ios_base::binary);
    while(input)
    {
        unsigned value;
        input.read(reinterpret_cast<char*>(&value),sizeof(unsigned));
        ....
    }
    input.close();
...

//write
    std::ofstream output(fname,std::ios_base::binary);
    for(std::map<unsigned,unsigned>::const_iterator iter =originalMap.begin();iter != originalMap.end();++iter)
    {
        unsigned temp = iter->first;
        output.write(reinterpret_cast<char*>(&temp),sizeof(unsigned));
        temp = iter->second;
        output.write(reinterpret_cast<char*>(&temp),sizeof(unsigned));
    }

Solution

  • They are running sequentially, essentially, shell script runs same console app in a loop...

    Then, on any "normal" operating system, there should be no problem.

    When the application terminates the streams are destroyed, so all the data that may be kept in cache by the C/C++ streams is written in the underlying OS streams, that are then closed.

    Whether the OS does some more caching is irrelevant - caching done by the operating system is transparent to applications, so, as far as applications are concerned, the data is now written in the file. If it is actually written on disk is of no concern here - the applications reading from the file will see the data in it anyway.

    If you think about it, without such a guarantee it would be complicated to do reliably any work on a computer! :)


    Update:

    std::ofstream output(fname,std::ios_base::binary);
    

    You should truncate the output file before writing on it, otherwise, if the input file was longer than the output, old data will still be lingering at the end of the file:

    std::ofstream output(fname,std::ios_base::binary | std::ios_base::trunc);