Advertisement

A Quick File I/O question

Started by July 24, 2000 01:13 AM
0 comments, last by shdaga 24 years, 5 months ago
what i want to know is simple(i think). If i have a file open for reading which i have wrote 3 records to, what is a good method for reading in a random record of data. Lets say im gonna match what i want to read to a records ID field. Lets see if i can post the code...

bool LoadCharacter(char *filename, char *chr_load_name)
{
//this funtion will load a character from a file into a character struct.
    
	character *chr;

	//code to search the file for a specified character determined by the name field goes here...
    ifstream fin(filename);
	fin.read((char *)(&chr), sizeof(chr));
	
	while(!strcmp(chr->name, chr_load_name))
	{
		if(fin.eof())
		{
			cout<<"\n Could not find character in file. ";
			getch();
			return false;
		}
		fin.read((char *)(&chr), (sizeof(chr)));
	}
    
	//found a match, so fill character struct with info

	return true;

}//end of LoadCharacter();
 
keep in mind that this is a work in progress. I guess what im really trying to find out is, will reading a record automatically move the file pointer to the next record or would i have to find another way of finding the record...I hope this isnt too confusing. --bah! who needs a signature?! Edited by - shdaga on 7/24/00 1:16:30 AM Edited by - shdaga on 7/24/00 3:41:37 AM
Here's a new dance everyone can do, do the Kirby:<(*.*<) <(^.^)> (>*.*)> <(^.^)> <(*.*<) (>^.^)>
Yes, doing a read causes the current file position to be updated.

To move around randomly in a file use seekg().

Assuming your records are fixed-length then you can do seekg(index * sizeof(record)) to move to a specific record. If they aren''t fixed length then you need to maintain a table somewhere that stores the offset of each record in the file or else just process each record like you''re doing already.

This topic is closed to new replies.

Advertisement