简体   繁体   中英

Preventing std::ifstream from creating an empty file

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM