是否有可能在文件不存在的情况下使用ios::in和ios::out打开fstream,而不会出现错误?
std::string filename { "test.txt" };
(void) std::ofstream(filename, std::ostream::app);
std::fstream file(filename);
或者,如果您需要更多的标志,例如 binary
,请使用:
std::string filename { "test.txt" };
(void) std::ofstream(filename, std::ofstream::app | std::fstream::binary);
std::fstream file(filename, std::fstream::in | std::fstream::out | std::fstream::binary);
std::fstream::create
,用于在请求读写模式时创建不存在的输出文件。#include <fstream>
ofstream out("test", ios::out);
if(!out)
{
cout << "Error opening file.\n";
return 1;
}
ifstream in("test", ios::in);
if(!in)
{
cout << "Error opening file.\n";
return 1;
}
如果发生错误,将显示消息并返回 1。但是,可以仅编译和执行 ofstream out("test", ios::out);
和 ifstream in("test", ios::in);
而不出现任何错误。无论哪种方式,都会创建文件 test。
std::fstream f("test.txt", std::ios_base::out);
f.close(); //file now exists always
f.open("test.txt", fstream::in | std::ios_base::out);
//f is open for read and write without error
我还没有检查过以确保它能够无误地打开,但我相信它应该是可以的。
#include <iostream>
#include <fstream>
using namespace std;
int main () {
fstream f("test.txt", fstream::in | fstream::out);
cout << f.fail() << endl;
f << "hello" << endl;
f.close();
return 0;
}
如果文件不存在,此代码将打印1
并不会创建"test.txt"文件。因此,在没有出现错误的情况下,无法打开和使用fstream读取不存在的文件。