fstream and ofstream

fstream and ofstream

本文关键字:ofstream and fstream      更新时间:2023-10-16

之间有什么区别

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.

这些评论还有一些很棒的地方。

看看他们在cplusplus.com上的页面。

CCD_ 5继承自CCD_ 6。fstream继承自iostream,后者继承自istreamstream。通常,ofstream只支持输出操作(即文本文件<<"hello"),而fstream同时支持输出和输入操作,但取决于打开文件时给出的标志。在您的示例中,默认情况下,打开模式为ios_base::in | ios_base::outofstream的默认打开模式为ios_base::out。此外,ios_base::out总是为流对象设置的(即使在参数模式中明确地没有设置)。

textfile仅用于输出,ifstream仅用于输入,fstream同时用于输入和输出时,使用ofstream。这会让你的意图更加明显。