c++ - fstream 和 ofstream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23258825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:23:04  来源:igfitidea点击:

c++ - fstream and ofstream

c++fstreamofstream

提问by Robin

What is the difference between:

有什么区别:

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

and

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

Are their function the same?

它们的功能一样吗?

采纳答案by user657267

ofstreamonly has methods for outputting, so for instance if you tried textfile >> whateverit would not compile. fstreamcan be used for input and output, although what will work depends on the flags you pass to the constructor / open.

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.

The comments have some more great points.

评论有一些更重要的观点。

回答by Danqi Wang

Take a look at their pages on cplusplus.com hereand here.

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

ofstreaminherits from ostream. fstreaminherits from iostream, which inherits from both istreamand stream. Generally ofstreamonly supports output operations (i.e. textfile << "hello"), while fstreamsupports both output and input operations but depending on the flags given when opening the file. In your example, the open mode is ios_base::in | ios_base::outby default. The default open mode of ofstreamis ios_base::out. Moreover, ios_base::outis always set for ofstream objects (even if explicitly not set in argument mode).

ofstream继承自ostream. fstream继承自iostream,它继承自istreamstream。一般ofstream只支持输出操作(即 textfile << "hello"),同时fstream支持输出和输入操作,但取决于打开文件时给出的标志。在您的示例中,ios_base::in | ios_base::out默认情况下为打开模式。的默认打开方式ofstreamios_base::out。此外,ios_base::out始终为 ofstream 对象设置(即使在参数模式下未明确设置)。

Use ofstreamwhen textfileis for output only, ifstreamfor input only, fstreamfor both input and output. This makes your intention more obvious.

使用ofstreamwhen textfileis for output only, ifstreamfor input only, fstreamfor both input and output. 这会让你的意图更加明显。