[英]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
,它继承自istream
和stream
。 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
仅用于输出时,使用ofstream
, ifstream
仅用于输入, fstream
用于输入和输出。 This makes your intention more obvious. 这使你的意图更加明显。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.