Search code examples
c++exceptionfstreamfile-handling

what happens if I delete the file onto which a c++ program is writing data to?


#include<iostream>
#include<string>
#include<fstream>
#include<unistd.h>
using namespace std;

int main(){
    fstream f;
    f.open("test.txt" , ios::app);
    string s="Hello";
    if(f.is_open()){
        cout << "File Open"<<endl;
        f << s;
        sleep(15);
        if(f.is_open()){
            cout << "Still Open" << endl;
        }else{
            cout << "Not Open" << endl;
        }
        s= "Hey \n";
        f<< s;
    }else{
        cout << "Not open" << endl;
    }
    f.close();
    }
}

This code will write contents to test.txt file upon normal execution. But if I delete the file while the program is running, then I find that the program throws no exception and it exits successfully. But I do not find the file text.txt after I deleted it.

What should I do to know whether writing to the file is happening successfully?


Solution

  • It depends on operating system you are using.

    On Windows, the OS will prevent you from removing such file in first place.

    On Linux, the OS will let you remove such file, but will keep handle to this file until it'll be freed by process which use it (in this case, when fstream will release resource).