Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failbit set when trying to read from file - why?

Tags:

c++

fstream

I'm trying to write a function that automatically formats XML-Strings; but I'm already failing when I try to read text from a file and write it into another one.

When I use my function sortXMLString()

bool FormatXML::sortXMLString()
{
    string XMLString;
    ifstream fin("input.txt");
    fin.open("input.txt", ios::in);
    ofstream fout("output.txt");
    fout.open("output.txt", ios::out);
    if (fin.is_open() && fout.is_open())
    {
        if (fin.good()) cout << "good" << endl;
        if (fin.fail()) cout << "fail" << endl;
        if (fin.bad()) cout << "bad" << endl;
        while (getline(fin, XMLString))
        {
            //TODO: Formatting
            fout << &XMLString << endl;
        }
        fin.close();
        fout.close();
    }
    else return false; 
    return true;
}

I will get the output "fail", but the function never enters the while-loop. The function returns true. It doesn't matter what I write into my input.txt (a single letter, a single number, multiple lines of text or even nothing), the failbit will always be set before getline can even be reached. Why is this/ how can I properly read out of my file?

like image 996
Thorlin Avatar asked Dec 01 '25 07:12

Thorlin


1 Answers

ifstream fin("input.txt"); will open the file with fin as stream object why calling open member function again ? same goes for fout object too.

Calling open on an already open stream fails, meaning the failbit flag is set to true.

Just open once

ifstream fin("input.txt");
ofstream fout("output.txt");
like image 115
P0W Avatar answered Dec 03 '25 21:12

P0W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!