difference between short & int

#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp,*fp1;
short i=10,a;
fp=fopen (“a.txt”,“wb”);
fwrite (&i,sizeof(short),1,fp);
fclose (fp);
fp=fopen (“a.txt”,“rb”);
fread (&a,2,1,fp);
printf ("%d",a);
fclose(fp);

}

this program shows correct output for data type short, btw shows garbage value for integer. can someone explain what happens if i use integer?

Please, do NOT ask same (slightly modified) question multiple times, it seems to me that we can solve your problems in one thread.

When you are inserting code, use code button in editor.

If you have problem with code, insert the one that’s not working (or better both), NOT the working one.

If you swap short with int in this program everything should work fine.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE *fp,*fp1;
    int i=10,a;
    fp=fopen ("a.txt","wb");
    fwrite (&i,sizeof(int),1,fp);
    fclose (fp);
    fp=fopen ("a.txt","rb");
    fread (&a,sizeof(int),1,fp);
    printf ("%d",a);
    fclose(fp);

}

you are using wrong constant in fread call again.

1 Like
//