Hello All!
I'm working on a bit of code and I ran into a problem. I am trying to make a program that writes data to a binary file. When the program is run again later (presumably after being terminated) it is supposed to read in the old directory file (also in binary). I am confident the data written is good (after viewing it in a hex editor), but since the data is a mixture of characters and integers, I am having trouble retrieving both the characters and the integers.
I feel like I may be using the wrong method. Any suggestions?

void getIndex()
{
	char Line[8];
	char *Tok;
	int count = 0;

	int *rawOffset;

	printf("Retrieving index: Please wait...");	

	while (fgets((char *) Line, sizeof(IndexDat), inDir) != NULL )
	{	
		Tok = strtok( Line, "\0");
		strncpy(&iDat[count].CCODE[0], Tok, 3);

		//The true offset is Line[4] to Line[7]
		rawOffset = &Line[4];
		iDat[count].offset = rawOffset;

		count++;
	fseek(inDir, 1, SEEK_CUR); //advance one more place to queue up the next entry
	}
	printf("All done. %d entries currently in database\n", count);

As it is, the code recovers some integer, but it seems to always be zero or "garbage". I was hoping to recover the data and store it in an array of matching structs for querying

If it helps, I am writing the data using;

fwrite(&iDat[c],sizeof(iDat[c]),1,outFile);

where iDat is the struct:

typedef struct
{
	char CCODE[4];
	long offset;
}IndexDat;

and c is an int and outFile is a FILE *

Thanks for your help!

If you are using fwrite() you should probably be using fread() , not fgets()

That sounds reasonable. Is there any way I can load the data into my struct? Otherwise, I'm not certain how to split the integer value from my char array...

Do the reverse of how you got the data into the file. fread() and fwrite() can be thought of as direct opposites.

This article has been dead for over six months. Start a new discussion instead.