【发布时间】:2021-03-22 09:24:40
【问题描述】:
如果找不到具有所提供路径的文件,则以下代码将创建一个空文件:
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?
有没有办法避免ifstream 的这种行为?如果找不到文件,我需要使操作失败,但它总是成功。对于这种行为,我是否必须退回到fopen?
【问题讨论】:
-
如果你以阅读模式打开它,那应该做你想做的事
标签: c++ c++11 file-io fstream iostream