Writing a structure into a file

mdzkhan's Avatar, Join Date: Jun 2008
Newbie Member
I am using the following code
typedef struct A {
int x;
int y;
int  z;

int main(void) {

 struct A A;
 struct A B;
FILE *fp;
A.x = 80000;
A.y = 40000;
A.z = 12345;

printf("%d %d %d\n", A.x, A.y, A.z);
fp = fopen("file.txt", "wb");
fwrite(&A, sizeof A, 3, fp);
fp = fopen("file.txt", "rb");
fread(&B, sizeof B, 1, fp);
printf("%d %d %d\n", B.x, B.y, B.z);
return 0;
But the file.txt is containing junk values when i open it . Please let me know what is wrong in my program.


Last edited by shabbir; 24Jun2008 at 20:22.. Reason: Code block
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Because you are writing it in binary mode.
Subrat_Mishra's Avatar, Join Date: Jun 2008
Newbie Member
Because you have assigned the value to int type variable beyond its range.