fstream and ofstream
fstream and ofstream
之间有什么区别
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
,后者继承自istream
和stream
。通常,ofstream
只支持输出操作(即文本文件<<"hello"),而fstream
同时支持输出和输入操作,但取决于打开文件时给出的标志。在您的示例中,默认情况下,打开模式为ios_base::in | ios_base::out
。ofstream
的默认打开模式为ios_base::out
。此外,ios_base::out
总是为流对象设置的(即使在参数模式中明确地没有设置)。
当textfile
仅用于输出,ifstream
仅用于输入,fstream
同时用于输入和输出时,使用ofstream
。这会让你的意图更加明显。
相关文章:
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 为什么 Clang 不允许"and"作为函数名称?
- 位阵列上的快速AND运算
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- BoostPython and CMake
- std::ofstream 作为类成员删除复制构造函数?
- OpenSSL BIO and SSL_read
- Gurobi GRBModel and GRBmodel in C++
- ofstream::close() 是否在 Linux 上调用同步?
- std::visit and std::variant usage
- SHBrowseForFolder with BIF_BROWSEFORCOMPUTER and SHGetPathFr
- 如何在软件代码中使用ofstream创建文件
- Directx12 and keystrokes
- Using ifstream, ofstream and fstream
- Openmp with ofstream and system command
- C++, regarding fprintf and ofstream
- Ifstream and Ofstream problems
- overriding istream and ofstream
- fstream and ofstream