【问题标题】:Unable to print from fstream无法从 fstream 打印
【发布时间】: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语句没有问题)

【问题讨论】:

  • 请具体说明您面临的错误
  • 我更新了更具体的帖子。只需运行程序,您就会明白我在说什么。

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


【解决方案1】:

你需要在 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 类,如果文件打开则关闭该文件。添加更多错误检查。您甚至可以从write_file() 中删除对print() 的呼叫,并单独呼叫print()

【讨论】:

  • 你能说出错误发生在首位的原因吗?
  • 出现这个问题是因为你没有将写和读分开。您应该打开文件,写入数据,然后关闭它。然后,要打印,您应该打开、读取数据、关闭它。在您的原始实现中,文件最终保持打开状态(来自 write_file),然后永远不会关闭。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多