i got an assigment, for tomorow, i have a text file, and i need to convert it to binary file.

text file for example:

2 - how many products
ipod 1000 2 - product name, price stock
playStation 23 9

i need to preper this binary file:
first the size, the lengh of the product name, the product name,

this is my code..

void ConverToBinary(FILE* fp,FILE* newFp)
{
	int size;

	fseek(fp,0,SEEK_SET);
		fscanf(fp,"%d\n",&size); 
		//write the size
		fwrite(&size,sizeof(int),1,newFp);
		
	ConvertStock(fp,newFp,size);
}

void ConvertStock(FILE* fp,FILE* newFp,int size)
{
	int len=0,i=0,flag=TRUE,cost,stock,y1,y2;
	char ch,*prod;
	long int location,locationLen;
	char x[256];

	locationLen = ftell(newFp);
//	fwrite(&i,sizeof(int),1,newFp);
	
	while (flag)
	{
		ch = fgetc(fp);
		if (ch == EMPTY)
			flag = FALSE;
		else if (ch =='\t')
		{
				fseek(newFp,locationLen,SEEK_SET);
				fwrite(&len,sizeof(int),1,newFp);
				fseek(newFp,location,SEEK_SET);

				fscanf(fp,"%d",&cost);
					fscanf(fp,"%d\n",&stock);
					fwrite(&cost,sizeof(int),1,newFp);
					fwrite(&stock,sizeof(int),1,newFp);
				len = 0 ;

					locationLen = ftell(newFp);
				//	fwrite(&i,sizeof(int),1,newFp);
		}
		else
		{
			len++;
			fwrite(&ch,sizeof(char),1,newFp);
			location = ftell(fp);
		}
	
	}

the thing is,
when i reading from it, its really a mess.
i am trying to move back and forward and probably it messes it up

You'd be much better off reading a line into a structure, then writing the structure. Very simple. One record after another.

You can't just blindly use fseek for the sake of using fseek and expect a file to have any useful format at all. If you back up in a file and write, you are writing over file data.

Second for Walt's recommendation - very clean and easy as well.

You'd be much better off reading a line into a structure, then writing the structure. Very simple. One record after another.

You can't just blindly use fseek for the sake of using fseek and expect a file to have any useful format at all. If you back up in a file and write, you are writing over file data.

ok, i was thinking of putting zero's in the places i need later to be rewrited,and then save the locations of the zero, afterwards write string, save the location, go back to the zero, write the lengh, and go back to the second place i saved...

its possible?

WaltP's approach is much much more simpler ....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.