binary file read problem

The file I am reading is a binary file. In that file the first I am reading names terminated by '\0'.Then I seekg to avoid reading the '\0'.When I use peek from this position I am able to see the correct value,then I read the historization interval. But after reading (historization Interval)when i peek it always returns -1,tellp() also returns -1.. I am unable to understand why the stream location becomes -1 after the reading after doing the seekg()


while(configFile.peek() != '\0')
{
configFile.read((char*)confRes[configStructCounter].pointName,1);
cout<<confRes[configStructCounter].pointName<<endl;
}
int pos =configFile.tellg();
pos= pos +1;
configFile.seekg(pos);
cout<<"The next character "<<configFile.peek()<<endl;
cout<<"The stream location after seek--->"<<configFile.tellg()<<endl;

configFile.read((char*)confRes[configStructCounter].historizationInterval,sizeof(short int));

cout<<"The next character "<<configFile.peek()<<configFile.tellg()<<endl; //-------->Here the value returned is -1 .After this in next loop also -1



configFile.read((char*)confRes[configStructCounter].attributeId,sizeof(char));
configFile.read((char*)confRes[configStructCounter].collectionId,sizeof(char));
configFile.read((char*)confRes[configStructCounter].arrayId,sizeof(char));
Last edited on
That doesn't make sense. If it is a binary file then you'll only read 1s; '\0' == NULL == 0. Try reading until EOF (while (!configFile.eof()).
Don't suggest people loop on eof() -- if anything goes wrong it becomes an infinite loop.

Always test against the good() -- and then take appropriate action depending on the reason for the lack of 'good'ness, whether it be eofbit or badbit or whatever.


I was pressed for time earlier, and I still don't want to look too hard into what could be wrong, but are you sure you opened the file with ios_base::binary? Because if you haven't, then tellx() and seekx() fail miserably (due to a design flaw in the implementation of the STL fstream classes).

Hope this helps.
due to a design flaw in the implementation of the STL fstream classes
What's that? Something to do with newline translation?
Don't suggest people loop on eof() -- if anything goes wrong it becomes an infinite loop.

Always test against the good()

Well, I didn't know that (!). That's somewhat alarming; I've always used eof. Perhaps while (file.good() && !file.eof())? Or does good() check for end-of-file as well?
Last edited on
hi guys,

You can input \0 in the binary file . I was able to read it. It will be read as 0.The problem is the person who has written the config file is putting a \0 to indicate the end of the pointName.

So i have to read till that to get the data.

Moreover i still am unable to understand why the tellg() returns -1. I have opened the file in
(ios::in| ios::binary)..

Still no clue why it fails...
Topic archived. No new replies allowed.