Hello every one this is basically extension to my previous question. i have write the short int value in file using
short int x= 254;
FILE * f1 = fopen("infile" ,"w");
fwrite (&x , 1 , sizeof(short int ) , f1 );
it working fine but when i tried to retrieve value like this
short int y ;
fread(&y , 2, 1 ,f1);
printf("%d" , y);
it gave me answer 8180 and next time 12276 so on… what should i do
actually I want to store short integers in my file and then retrieve them one by one am i doing it wrong kindly guide me
If you want to read back from the file you just wrote to, you need to open it with “w+” options to allow you to read and write. You then need to seek back to the beginning of the file:
Alternatively, you could read / write as separate operations:
Note that in your original code you weren’t checking the return value of fread to check whether you’d actually read anything from the file. If you’d done that you’d have seen it was returning 0 to indicate that it read 0 bytes. If you’re not reading anything from the file and you’re not initialising
ythen it’s likely to just be a random number.