防止std::ifstream创建空文件



如果找不到具有提供路径的文件,以下代码将创建一个空文件:

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吗?

这个std::basic_filebuf::open引用包含一个方便的表,其中列出了不同标志的情况。正如您所看到的,每次使用app时,行为都是在不存在的情况下创建一个新文件。

有一种方法可以解决这个问题:使用app标志在不使用的情况下打开。这样打开就会失败,然后你可以检查一下。如果没有失败,则关闭该文件,然后使用app再次打开。

最新更新