简体   繁体   English

c ++ - fstream和ofstream

[英]c++ - fstream and ofstream

What is the difference between: 有什么区别:

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

and

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

Are their function the same? 他们的功能是一样的吗?

ofstream only has methods for outputting, so for instance if you tried textfile >> whatever it would not compile. ofstream只有输出方法,所以例如你试过textfile >> whatever它不能编译。 fstream can be used for input and output, although what will work depends on the flags you pass to the constructor / open . 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.

The comments have some more great points. 评论有一些更好的观点。

Take a look at their pages on cplusplus.com here and here . 这里这里查看 cplusplus.com上的页面。

ofstream inherits from ostream . ofstream继承自ostream fstream inherits from iostream , which inherits from both istream and stream . fstream继承自iostream ,它继承自istreamstream Generally ofstream only supports output operations (ie textfile << "hello"), while fstream supports both output and input operations but depending on the flags given when opening the file. 通常, ofstream仅支持输出操作(即textfile <<“hello”),而fstream支持输出和输入操作,但取决于打开文件时给出的标志。 In your example, the open mode is ios_base::in | ios_base::out 在您的示例中,打开模式是ios_base::in | ios_base::out ios_base::in | ios_base::out by default. 默认情况下ios_base::in | ios_base::out The default open mode of ofstream is ios_base::out . ofstream的默认打开模式是ios_base::out Moreover, ios_base::out is always set for ofstream objects (even if explicitly not set in argument mode). 此外,始终为ofstream对象设置ios_base::out (即使未在参数模式中明确设置)。

Use ofstream when textfile is for output only, ifstream for input only, fstream for both input and output. textfile仅用于输出时,使用ofstreamifstream仅用于输入, fstream用于输入和输出。 This makes your intention more obvious. 这使你的意图更加明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM