Reputation: 32740
The following code will create an empty file if a file with the supplied path is not found:
std::ifstream file;
file.open(path, std::ios::in | std::ios::binary | std::ios::app);
//file.open(path, std::ios::in | std::ios::binary); will set fail() to true
if (!file.is_open())
throw std::runtime_error("File could not be opened."); //never reached
file.seekg(0, file.end);
size_t size = file.tellg();
file.seekg(0, file.beg);
char* buffer = new char[size];
file.read(buffer, size);
file.close();
if (file.fail())
throw std::runtime_error("Error reading file."); //why with only std::ios::in | std::ios::binary?
Is there a way to avoid this behavior of ifstream
? I need to make the operation fail if the file is not found but it always succeeds. Do I have to fall back to fopen
for this behavior?
Upvotes: 2
Views: 624
Reputation: 409136
This std::basic_filebuf::open
reference contains a handy table what happens with the different flags. And as you can see every time app
is used the behavior is to create a new file if it doesn't exist.
There is a way around this: Open without using the app
flag. This way the open would fail which you can then check for. If it doesn't fail, then you close the file and open again with app
.
Upvotes: 4