【发布时间】:2015-11-30 15:12:33
【问题描述】:
我正在尝试通过关闭打开的文件并以新模式打开来将文件的打开模式从 ios::in | ios::out 更改为仅 ios::out。我已经将我的fstream 存储在一个类file_handler 中,其成员函数从文件读取和写入文件。但是在新模式下打开后,这些功能似乎不起作用。这是我的代码(针对这里的问题改编自一个更大的程序):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class file_handler
{
protected:
fstream file;
string path;
public:
void file_open();
void print();
};
void file_handler::file_open()
{
cout << "\n ENter filename : ";
cin >> path;
file.open(path, ios::out | ios::in);
}
class html : public file_handler
{
string title, body;
public:
void get_data();
void write_file();
};
void html::get_data()
{
cout << "\n enter title : ";
cin >> title;
cout << "\n enter body : ";
fflush(stdin);
cin >> body;
}
void html::write_file()
{
file.close();
file.open(path, ios::out);
file.seekg(0);
file << "\n title : " << title << "\n body : " << body;
print();
}
void file_handler::print()
{
cout << "\n\n Here is your html file";
string temp;
while(getline(file, temp))
cout << temp << endl;
}
int main()
{
html F;
F.file_open();
F.get_data();
F.write_file();
}
您能否指出错误并提出解决方案。任何帮助将不胜感激。
遇到的错误:
1.我要创建的文件在电脑上找不到(write_file()可能不行)
2.print()不“打印文件”(虽然它执行cout语句没有问题)
【问题讨论】:
-
请具体说明您面临的错误
-
我更新了更具体的帖子。只需运行程序,您就会明白我在说什么。