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
c++ - fstream and ofstream
提问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
ofstream
only has methods for outputting, so for instance if you tried textfile >> whatever
it would not compile. fstream
can 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 上的页面。
ofstream
inherits from ostream
. fstream
inherits from iostream
, which inherits from both istream
and stream
. Generally ofstream
only supports output operations (i.e. textfile << "hello"), while fstream
supports 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::out
by default. The default open mode of ofstream
is ios_base::out
. Moreover, ios_base::out
is always set for ofstream objects (even if explicitly not set in argument mode).
ofstream
继承自ostream
. fstream
继承自iostream
,它继承自istream
和stream
。一般ofstream
只支持输出操作(即 textfile << "hello"),同时fstream
支持输出和输入操作,但取决于打开文件时给出的标志。在您的示例中,ios_base::in | ios_base::out
默认情况下为打开模式。的默认打开方式ofstream
是ios_base::out
。此外,ios_base::out
始终为 ofstream 对象设置(即使在参数模式下未明确设置)。
Use ofstream
when textfile
is for output only, ifstream
for input only, fstream
for both input and output. This makes your intention more obvious.
使用ofstream
when textfile
is for output only, ifstream
for input only, fstream
for both input and output. 这会让你的意图更加明显。