c++ - fstream and ofstream

18

什么是以下两者之间的区别:

fstream texfile;
textfile.open("Test.txt");

ofstream textfile;
textfile.open("Test.txt");

它们的功能是相同的吗?

2个回答

16

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.

这些评论还有更多很棒的观点。


5
同时,ofstream::open 的默认打开模式为 ios_base::out,而 fstream::open 的默认打开模式为 ios_base::in | ios_base::out - M.M
8
此外,在使用std::fstream时,如果文件不存在,尝试打开文件将会失败。而std::ofstream则不同,如果找不到文件,它会创建一个新的文件。如果要在构造函数或open()函数中调用std::fstream并且想覆盖原有文件,需要添加std::ios_base::trunc标志。 - David G

3
请查看他们在cplusplus.com上的页面,分别是这里这里ofstream继承自ostream。而fstream则继承自iostream,后者同时继承自istreamstream。通常情况下,ofstream只支持输出操作(例如将文本文件写入“hello”),而fstream则支持输入和输出操作,但取决于打开文件时给定的标志。在您的示例中,默认情况下打开模式为ios_base::in | ios_base::out。而ofstream的默认打开模式是ios_base::out。此外,对于ofstream对象,始终设置ios_base::out(即使在参数模式中明确未设置)。
textfile仅用于输出时,请使用ofstream;当仅用于输入时,请使用ifstream;当需要进行输入和输出时,请使用fstream。这样可以更清晰地表达您的意图。

请勿引用cppreference.com,谢谢。 - Cheers and hth. - Alf
@Cheersandhth.-Alf cppreference.com 更美观,但谷歌搜索 c++ fstream 时返回 cplusplus.com。cppreference.com 相对于 cplusplus.com 的其他优势是什么? - Danqi Wang
1
@DanqiWang:由于更好的同行评审,通常更正确。 - Cheers and hth. - Alf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接