什么是以下两者之间的区别:
fstream texfile;
textfile.open("Test.txt");
和
ofstream textfile;
textfile.open("Test.txt");
它们的功能是相同的吗?
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.
这些评论还有更多很棒的观点。
ofstream
继承自ostream
。而fstream
则继承自iostream
,后者同时继承自istream
和stream
。通常情况下,ofstream
只支持输出操作(例如将文本文件写入“hello”),而fstream
则支持输入和输出操作,但取决于打开文件时给定的标志。在您的示例中,默认情况下打开模式为ios_base::in | ios_base::out
。而ofstream
的默认打开模式是ios_base::out
。此外,对于ofstream
对象,始终设置ios_base::out
(即使在参数模式中明确未设置)。textfile
仅用于输出时,请使用ofstream
;当仅用于输入时,请使用ifstream
;当需要进行输入和输出时,请使用fstream
。这样可以更清晰地表达您的意图。c++ fstream
时返回 cplusplus.com。cppreference.com 相对于 cplusplus.com 的其他优势是什么? - Danqi Wang
ofstream::open
的默认打开模式为ios_base::out
,而fstream::open
的默认打开模式为ios_base::in | ios_base::out
。 - M.Mstd::fstream
时,如果文件不存在,尝试打开文件将会失败。而std::ofstream
则不同,如果找不到文件,它会创建一个新的文件。如果要在构造函数或open()
函数中调用std::fstream
并且想覆盖原有文件,需要添加std::ios_base::trunc
标志。 - David G