Reputation: 23
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);
}
Upvotes: 2
Views: 9755
Reputation: 41017
To go to the end of the file:
ifstream is;
is.open( "file.txt", ios::binary );
is.seekg (0, ios::end);
To get the length of the file (when at the end), use tellg
which returns the absolute position of the get pointer.
length = is.tellg();
To go back to the beginning use seekg
again, this sets the position of the put pointer.
is.seekg (0, ios::beg);
If you have tried this could you be more specific about what isn't working?
Upvotes: 6
Reputation: 121849
You probably want "seekg(ios_base::beg)":
http://bytes.com/topic/c/answers/602553-ifstream-seeking
http://www.cplusplus.com/reference/iostream/istream/seekg/
If it's "not working", two things to try:
1) check position "tellg()"
2) check error status (eofbit, failbit, badbit)
Upvotes: 0