I am developing an MFC application using Visual C++ 2010
I am reading data for one file but It seems seekg is not working
Here is my code
//Transaction is a class i have defined before
void displayMessage(CString message)
{
MessageBox(NULL,message,L"error",MB_OK | MB_ICONERROR);
}
///////////////////////////////
ifstream input;
input.open("test.dat" , ios::binary );
if( input.fail() )
{
CString mess;
mess = strerror( errno );
mess.Insert(0,L"Error\n");
displayMessage(mess);
}
Transaction myTr(0,myDate,L"",0,0,L""); // creating an object of transaction
unsigned long position = 0;
while(input.read( (char *) &myTr , sizeof(Transaction)))
{
if(myTr.getType() == 400 )
position = (unsigned long)input.tellg() - sizeof(Transaction);
}
CString m;
m.Format(L"Pos : %d",position);
displayMessage(m);
input.clear();//I also tried removing this line
input.seekg(position,ios::beg );
m.Format(L"get pos: %d",input.tellg());
displayMessage(m);
input.close();
The first displayMessage shows This : Pos : 6716 But second one showes : get pos: 0
Why seekg is not working ?
Thanks
The problem is that
CString.Format()is a varargs function andbasic_istream::tellg()returns apos_typewhich isn’t a type that can be passed as a vararg agument so you get undefined behavior.If you want to pass the position you get bace from
tellg()toCString::Format()you’ll need to cast it or put it in a temporary, intermediate variable: