If you want to open a file for i/o even if it does not exist, try to open first for inp/out and if that fails then open for output (which will create the file) and then try again to open for inp/out. If that fails a second time then there is a problem. Something like (in this example ofn is file name and rout is error code):
1 2 3 4 5 6 7 8 9 10 11 12 13 14
constauto outopt { std::ios::binary | std::ios::in | std::ios::out};
// Try to open output file assuming already exists
if (ofs.open(ofn, outopt); !ofs.is_open())
// If output open fail, try to open for output without specifying in as may not already exist
if (ofs.open(ofn, std::ios::binary | std::ios::out); ofs.is_open()) {
// If new file created OK, then close and re-open for input/output
ofs.close();
ofs.open(ofn, outopt); // Try to open output file for input/output again
}
// Has the output file opened ok?
if (!ofs.is_open())
return (std::cout << "Cannot open output file " << ofn << '\n'), rout;