views:

85

answers:

2

Any idea why the following would fail?

std::fstream i(L"C:/testlog.txt", std::ios::binary | std::ios::in);
int test = 0;
i >> test;

fail() is returning true. The file exists and is opened.

I checked i._Filebuffer._Myfile._ptr and it is pointer to a buffer of the file so I don't see why it is failing.

+2  A: 

You're opening the file in binary mode. The extraction operators were meant to be used with text files. Simply leave out the std::ios::binary flag to open the file in text mode.

If you actually do have a binary file, use the read() function instead.

Edit: I tested it too, and indeed it seems to work. I got this from CPlusPlus.com, where it says:

In binary files, to input and output data with the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...).

Together with the description of ios::binary, which simply states "Consider stream as binary rather than text.", I'm utterly confused now. This answer is turning into a question of its own...

Thomas
It works perfectly with GCC, though.
AndiDog
Opening the file in binary mode should have no effect - all that does is control expension of characters like '\n' - I've just tested this, BTW.
anon
@Thomas It says they are "not efficient" (whatever that might mean), not that they don't work.
anon
@Thomas: The binary operator has little to do with the stream operators. It is basically indicating that no text transformation is required when reading from the file. Now by text transformation I mean the end of line sequence. The "\n" is translated into the end of line sequence on output and the end of line sequence is translated into "\n" on input. That is __ALL__ the difference between binary and text mode. It has no other affect. (Though this may cost a tiny amount of processing this does not make the stream operators significantly less effecient).
Martin York
Then, using << and >> on a binary file might confuse the stdlib, if \r characters suddenly crop up. Also, I find the phrase "data may not use the separation codes used by text files to separate elements" very confusing. I dunno...
Thomas
Better don't trust cplusplus.com , btw. It teaches C++ in terms of implementations, not in terms of standards and uses imprecise terms. Looking into a standard draft (or generally accepted sites, like the C++ FAQ) is way better.
Johannes Schaub - litb
+1  A: 

The following:

#include <fstream>
#include <iostream>
using namespace std
int main() {
    std::fstream i("int.dat" , std::ios::binary | std::ios::in);
    int test = 0;
    if ( i >> test  ) {
        cout << "ok" << endl;
    }
}

prints "ok" when given a file containing the characters "123". Please post a similar short test that illustrates your code failing.

anon