Search code examples
c++ofstream

C++ Catch if the file was removed


I have some basic code that runs in a loop and writes to file. It looks along the lines of:

std::ofstream myFile;
myFile.open("file.txt", std::ofstream::out);
while (true)
{
    if (myFile.is_open() && myFile.good())
    {
        myFile << "test" <<std::endl;
    }
    if (myFile.fail())
    {
        std::cout << "Error\n";
    }
}

Everything works fine and errors if I manually insert a myFile.setstate() and set it to fail.

However, if I have the program writing to a file in a loop and then I manually go ahead and delete the file... The program appears to continue writing to file as if it still exists. No error is thrown. I thought maybe using flush() would work since I expected it to set the failbit, but the behaviour didn't seem to change. What am I doing wrong?

Is there a way to check if the file suddenly went missing, without resorting to trying to call open() again? (I'm trying to avoid .open() and .close() in a loop. Rather open at start, and then have it closed when it goes out of scope.)


Solution

  • I don't believe there's a portable way to do this. Many operating systems are designed so that if you delete a file that's being written to, the file appears deleted but still exists until the last program writing to it closes. Others don't even let you delete files that are being written to at all. The C++ standard doesn't have any guarantees about what should happen in this case, so I think you'll need to use a platform-specific API to test for whether the file still exists as you're writing to it.