This topic is now archived and is closed to further replies.


A Quick File I/O question

Recommended Posts

shdaga    122
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); *)(&chr), sizeof(chr));
	while(!strcmp(chr->name, chr_load_name))
			cout<<"\n Could not find character in file. ";
			return false;
		} *)(&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

Share this post

Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
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.

Share this post

Link to post
Share on other sites