【发布时间】:2020-12-16 00:44:57
【问题描述】:
我试图了解std::ofstream 和std::fstream 之间的区别。我有这个代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
//create an output stream to write to the file
//append the new lines to the end of the file
ofstream myfileI ("input.txt", ios::app);
if (myfileI.is_open())
{
myfileI << "\nI am adding a line.\n";
cout << myfileI.fail() << "\n";
myfileI << "I am adding another line.\n";
cout << myfileI.fail() << "\n";
myfileI.close();
}
else cout << "Unable to open file for writing";
失败位返回 0,所以它正在写入。
但是当我使用完全相同的代码但使用 fstream 而不是 ofstream 时,失败位返回 1。
input.txt 就是这样:
Read and write to this file.
What am I doing here?
This is not a good example of a file
【问题讨论】:
-
请edit 向我们展示失败程序。