I am trying to write an integer to a binary file and then read the same thing. However, my program reads a different number than the one that was written. What am I doing wrong?
unsigned short int numToWrite = 2079;
// Write to output
FILE *write_ptr;
write_ptr = fopen("test.bin","wb"); // w for write, b for binary
printf("numToWrite: %d\n", *(&numToWrite));
fwrite(&numToWrite, sizeof(unsigned short int), 1, write_ptr); // write 10 bytes from our buffer
fclose(write_ptr);
// Read the binary file
FILE *read_ptr = fopen(filename, "rb");
if (!read_ptr) {
perror("fopen");
exit(EXIT_FAILURE);
}
unsigned short int* numToRead = malloc(sizeof (unsigned short int));
fread(numToRead, sizeof(unsigned short int), 1, read_ptr);
printf("numToRead: %d\n", *numToRead);
free(numToRead);
fclose(read_ptr);
The output is this:
numToWrite: 2079
numToRead: 26964
filenameis undefined. There are also several undeclared functions. Please provide a complete example.