Another way to see what is actually in the file is to cast the address of an int to the address of a char.
Now, you can't just read two bytes into an int variable and expect to get something meaningful unless you know what's in the other bytes.
Also, the order in which the bytes are stored is processor-dependent, since compilers usually store int data in the "natural mode" of the processor (big-endian vs little-endian).
Try this on your machine to see if you get any insight into why you could get the results that you saw. I have left the fwrite() the way that you had it, and read the bytes back in with a corresponting fread().
In any program that you intend to use or release for others to use, you should always have lots of error checking (I have left it as an exercise).
On Intel machines (Windows as well as Linux), the file data.txt consisted of exactly two bytes: 0xdc and 0x05.
Code:
#include <stdio.h>
int main()
{
FILE *fp;
int i;
int myValue;
int inValue;
unsigned char *ChPoint;
myValue = 1500;
ChPoint = (unsigned char *)&myValue;
printf("sizeof(myValue) = %d\n", sizeof(myValue));
printf("myValue = %d, (%08x hex)\n", myValue, myValue);
for (i = 0; i < sizeof(myValue); i++) {
printf("byte %d = %02X\n", i, *(ChPoint + i));
}
/* write the bytes */
fp = fopen("data.txt", "wb"); /* should do error checking */
fwrite (&myValue, 2, 1, fp); /* should do error checking */
fclose(fp);
/* read two bytes into an integer */
inValue = 0;
printf("Before reading: inValue = %d (%08x hex)\n", inValue, inValue);
fp = fopen("data.txt", "rb"); /* should do error checking */
fread(&inValue, 2, 1, fp); /* should do error checking */
fclose(fp);
printf("After reading: inValue = %d (%08x hex)\n\n", inValue, inValue);
/* read two bytes into an integer */
inValue = -1;
printf("Before reading: inValue = %d (%08x hex)\n", inValue, inValue);
fp = fopen("data.txt", "rb"); /* should do error checking */
fread(&inValue, 2, 1, fp); /* should do error checking */
fclose(fp);
printf("After reading: inValue = %d (%08x hex)\n", inValue, inValue);
return 0;
}
Regards,
Dave