无法从fstream打印

时间:2015-11-30 15:12:33

标签: c++ file c++11 io fstream

我正在尝试通过关闭打开的文件并在新模式下打开,将文件的打开模式从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.我想要创建的文件在PC上找不到(write_file()可能不起作用)
2. print()不“打印文件”(尽管它执行cout语句没有问题)

1 个答案:

答案 0 :(得分:0)

您需要在write_file()中关闭文件:

void html::write_file()
{
    file.close();
    file.open(path, ios::out);
    file.seekg(0);
    file << "\n title : " << title << "\n body : " << body;
    file.close();
    print();
}

然后在print()中,你应该重新打开它:

void file_handler::print()
{
    cout << "\n\n Here is your html file";
    file.open(path);
    string temp;
    while (getline(file, temp))
        cout << temp << endl;
    file.close();
}

我建议检查file.isOpen()以确保您实际打开该文件。检查运行目录中的输出文件。

此外,我建议将RAII与文件一起使用。向您的file_handler类添加析构函数,如果文件打开则关闭该文件。添加一些错误检查。您甚至可以从print()移除对write_file()的来电,并分别致电print()