lundi 30 novembre 2015

Unable to print from fstream

I am trying to change a file's open mode from ios::in | ios::out to only ios::out by closing the open file and opening in the new mode. I have stored my fstream inside a class file_handler whose member functions read and write from/to the file. But after opening in the new mode, the functions do not seem to work.Here's my code (adapted from a bigger program for the question 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();
}

Can you point out the mistake(s) and kindly suggest a solution. Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire