无法从 fstream 打印

Unable to print from fstream

我正在尝试通过关闭打开的文件并以新模式打开文件,将文件的打开模式从 ios::in | ios::out 更改为仅 ios::out。我将我的 fstream 存储在 class file_handler 中,其成员函数读取和写入 from/to 文件。但是在新模式下打开后,这些功能似乎并没有 work.Here 我的代码(针对这里的问题改编自一个更大的程序):

#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()不会"print the file"(虽然它执行cout语句没问题)

您需要在 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 class 添加析构函数,如果文件打开则关闭文件。添加更多错误检查。您甚至可以从 write_file() 中删除对 print() 的调用,然后单独调用 print()