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?