Jump to content


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


1 reply to this topic

#1 Hyper

    Valued Member

  • Members
  • PipPipPip
  • 195 posts

Posted 11 April 2010 - 09:32 PM

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 now -- http://msdn.microsof...51c(VS.80).aspx
“You may be disappointed if you fail, but you are doomed if you don't try.”
Beverly Sills

#2 .oisyn

    DevMaster Staff

  • Moderators
  • 1842 posts

Posted 12 April 2010 - 11:12 AM

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:
[code=c++]out << in.rdbuf();[/code]
In other words, if you insert a streambuf into a stream it'll just copy everything until EOF.
C++ addict
-
Currently working on: the 3D engine for Tomb Raider.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users