[C++] I/O ios::iostate question

5ccedf5e0f538b594eb578f003ade3eb
0
Hyper 96 Apr 11, 2010 at 21:32

Hello, whomever.

My questions are as follows:
- Is the state flag literally set to “0” upon failure and “1” upon success?
- Is there a way to obtain a more ‘informative’ reason, as to why it returned an error?
- Am I missing something, or doing something wrong?

The code was compiled using MSVC 6.0 on Windows XP: SP2.
The code compiles fine. The program runs fine. The bit always returns “0” upon failure; Why?

#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;

void StreamCopy(ostringstream &buffer) {

    // open original file
    ifstream forig("bytes.dat", ios::in | ios::binary);

    // open copy file
    ofstream fcopy("bytes2.dat", ios::in | ios::binary | ios::trunc);

    int b = 0; // count of characters copied
    int c;

    // main loop
    while (1) {

        // get a character
        c = forig.get();

        // check for end-of-file
        if (forig.eof()) {
            buffer << "ios::iostate = " << buffer.rdstate() << endl;
            break;
        }

        if (forig.fail()) {
            buffer << "ios::iostate = " << buffer.rdstate() << endl;
            break;
        }

        // write character
        fcopy.put(char(c));

        // increment byte count
        b++;
    }

    // close files
    forig.close();
    fcopy.close();

    // report results
    buffer << "Binary copy of " << b << " characters" << endl << endl;
    cout << buffer.str();
}

int main() {

    ostringstream Test;
    StreamCopy(Test);

    return 0;
}

Thanks. :)

EDIT: Sorry, I found an MSDN link just nowhttp://msdn.microsoft.com/en-us/library/04z0z51c(VS.80).aspx

1 Reply

Please log in or register to post a reply.

340bf64ac6abda6e40f7e860279823cb
0
_oisyn 101 Apr 12, 2010 at 11:12

It’s because you call rdstate() on ‘buffer’ instead of on ‘forig’. Btw, if you want to fill a stream with the contents of another, you can just do:

out << in.rdbuf();

In other words, if you insert a streambuf into a stream it’ll just copy everything until EOF.