Im having a small problem with my code. I have been trying to read some information from the end of a random access file then repositioning the cursor at the beginning of the file. So far seekg has not been working. Here is my code:
void main ()
{
AssignData FileOut;
AssignData FileIn;
ofstream OutData("Data.dat", ios::out | ios::app | ios::binary);
ifstream InData("Data.dat", ios::in);
cout <<"Writing to file" << endl;
if (!OutData)
{
cout<<"File does not exist"<<endl;
exit(1);
}
//read through file
while (InData.read( reinterpret_cast< char * >( &FileIn ),sizeof( AssignData ) ))
{
}
FileIn.DisplayFileContent();//displays the last line in the file
FileOut.setInfo();//allows user to add another record
//Writes record to file
OutData.write( reinterpret_cast< const char * >( &FileOut ), sizeof(AssignData) );
OutData.close();
cout << endl<<endl;
//Reads the first record from the file
InData.seekg(0);
while (InData.read( reinterpret_cast< char * >( &FileIn), sizeof(AssignData) ))
{
// display record
if ( (FileIn.getID() != 0) || (FileIn.getID()!=NULL) )
{
FileIn.DisplayFileContent();
}
}
InData.close();
_getch();
exit(0);
}
To go to the end of the file:
To get the length of the file (when at the end), use
tellgwhich returns the absolute position of the get pointer.To go back to the beginning use
seekgagain, this sets the position of the put pointer.If you have tried this could you be more specific about what isn’t working?