I have following code opening a stream and writing to it and then removing it, again trying to write it. Is there a way to get fstream object get notified of non existent file and recreate file (i know i can use stat to check but i am wondering if there is a state change in stream object itself)
#include <iostream> // std::cout
#include <fstream> // std::fstream
#include <unistd.h>
#include <sys/stat.h>
int main () {
std::fstream fs;
fs.open ("test.txt",std::fstream::out);
if (fs.is_open())
{
fs << "lorem ipsum";
std::cout << "Operation successfully performed\n";
std::cout<<fs.fail()<<std::endl;
unlink("test.txt");
fs << "more lorem ipsum";
fs.write("hi",2);
fs.write("hi",2);
fs.write("hi",2);
fs.write("hi",2);
fs.write("hi",2);
std::cout<<fs.fail()<<std::endl;
fs.close();
}
else
{
std::cout << "Error opening file";
}
return 0;
}
I have tried
is_open()
good()