Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading /Writing structure

Status
Not open for further replies.

sajiv77

Programmer
Jan 2, 2002
14
IN
How do i wrtie more than one structure to a same file and then read it?





Here is a sample program i wrote.Tell me whats wrong with it





#include <stdio.h>





#define WRD 2


typedef unsigned char byte;





typedef struct


{


byte hr;


byte trans_no[WRD];


} ABC;





typedef struct


{


byte trans_no[WRD];


}XYZ;





main()


{





ABC ab;


ab.hr=9;


ab.trans_no[WRD]=20;





FILE *fp;


fp = fopen(&quot;testfile&quot;,&quot;w&quot;);





fwrite(&ab,sizeof(ABC),1,fp);


// fclose(fp);





XYZ xy;


xy.trans_no[WRD]=100;


// fp = fopen(&quot;testfile&quot;,&quot;a&quot;);


fwrite(&xy,sizeof(XYZ),1,fp);


fclose(fp);


FILE *fp1;





fp1 = fopen(&quot;testfile&quot;,&quot;r&quot;);


fread(&ab,sizeof(ABC),1,fp1);





printf(&quot;Hour is %u \n&quot;,ab.hr);


printf(&quot;Number is %d \n&quot;,ab.trans_no[WRD]);





// fclose(fp1);





// fp1 = fopen(&quot;testfile&quot;,&quot;r&quot;);


fread(&xy,sizeof(XYZ),1,fp1);


printf(&quot;Number from XYZ is %d \n&quot;,xy.trans_no[WRD]);





fclose(fp1);





}





 
the trouble with your code maybe that you are declaring variables in different lines in your code other than at the start. This is C not C++. In C you have to declare your XYZ xyz; and FILE *fp1; at the start before process begins.

this was found without looking for other faults if there are any. Hoping to get certified..in C programming.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top