c ++ - fstream和ofstream

Rob*_*bin 10 c++ fstream ofstream

有什么区别:

fstream texfile;
textfile.open("Test.txt");
Run Code Online (Sandbox Code Playgroud)

ofstream textfile;
textfile.open("Test.txt");
Run Code Online (Sandbox Code Playgroud)

他们的功能是一样的吗?

use*_*267 9

ofstream只有输出方法,所以例如,如果你尝试textfile >> whatever它不会编译.fstream可以用于输入和输出,虽然将起作用取决于您传递给构造函数/的标志open.

std::string s;
std::ofstream ostream("file");
std::fstream stream("file", stream.out);

ostream >> s; // compiler error
stream >> s; // no compiler error, but operation will fail.
Run Code Online (Sandbox Code Playgroud)

评论有一些更好的观点.

  • 而且,在`std :: fstream`的情况下,如果文件不存在,尝试打开文件将失败.这与`std :: ofstream`相反,如果找不到文件,它会创建一个文件.在调用构造函数时,必须将`std :: ios_base :: trunc`标志添加到掩码中,或者在`std :: fstream`上添加`open()`. (6认同)
  • 另外,`ofstream :: open`默认为openmode`ioos_base :: out`,`fstream :: open`默认为`ios_base :: in | 的ios_base :: out` (2认同)