3

I am trying to read from binary file on UNIX. The file exists and has several data information in it.

The code looks like this:

fstrean fstrHandler;

string strFileName;

char Buf[30000];

fstrHandler.open(strFileName.c_str(), ios::in | ios::binary);

fstrHandler.seekp(0, std::ios_base::beg);

std::cout<< "Posi before read= "<< fstrHandler.tellg()<<endl; //*** Show after running 0

fstrHandler.read (Buf, 400);

std::cout<< "Posi after read= "<< fstrHandler.tellg()<<endl; //*** Show after running 0

std::cout<< " gcount ()= "<< fstrHandler.gcount ()<< << endl; //*** Show after running 0

if (fstrHandler.eof ()) {
       fstrHandler.clear();
}

After the read I get that the position in file is still zero zero, but the file is not empty.

Tim Post
  • 33,371
  • 15
  • 110
  • 174
Boris Raznikov
  • 2,373
  • 10
  • 34
  • 56

1 Answers1

2

Try seekg rather than seekp, and is there 400 bytes in the file? this appears to work okay for me, if you input a file that contains more than 400 bytes. If less, then the tellg after read reports -1, but gcount() is correct.

Also, after opening the file - test to see if the file was indeed opened e.g.

if (fstrHandler)
{
// do stuff
}
else
  std::cerr << "foo bar" << std::endl;
Nim
  • 33,299
  • 2
  • 62
  • 101
  • That condition will always evaluate true. There's an `operator!` for that though, or `good()`, or `fail()`, or `is_open()`. – jweyrich Feb 02 '11 at 13:01
  • 1
    @jweyrich: if (stream) isn't always true [after opening](http://codepad.org/ARjqICEB), and it's the opposite of op!, which is itself the same as fail(). Don't use good(). – Fred Nurk Feb 02 '11 at 13:05
  • @Fred Nurk: there's an `operator bool()`? I always thought the `operator!` would require it to be explicitly used. Seems I've been wrong ever since. Why not use good()? It checks bad/eof/fail, which seems okay in this case too. – jweyrich Feb 02 '11 at 13:11
  • @Fred Nurk: Oh nevermind, I found the answer to my 1st question [here](http://stackoverflow.com/questions/1334858/why-dont-iostream-objects-overload-operator-bool). Nice catch :-) – jweyrich Feb 02 '11 at 13:19
  • @jweyrich: Good() tests all three, but eof() being true does not imply fail() (which actually checks failbit and badbit) is true. – Fred Nurk Feb 02 '11 at 13:20
  • @Fred Nurk: sure. But it's okay to use it in the presented scenario, unless OP wants to distinguish the cause, which doesn't seem to be the case as he didn't have any condition. – jweyrich Feb 02 '11 at 13:28
  • @jweyrich: It is sometimes equivalent. The problem is the sometimes. If you never use good(), you never have a problem remembering when it is equivalent and when it isn't. It is very, *very* rare to want to know eofbit might be set but fail() is false; thus good() should very, *very* rarely be used. – Fred Nurk Feb 02 '11 at 13:29