简体   繁体   中英

Writing and reading a binary file in c

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

man printf

Length modifier

h - A following integer conversion corresponds to a short or unsigned short argument, ...

Conversion specifiers

d,i - The int argument is converted to signed decimal notation.

Format of the format string

...
Each conversion specification is introduced by the character %, and ends with a conversion specifier. In between there may be (in this order) zero or more flags, an optional minimum field width, an optional precision and an optional length modifier.

You're using unsigned short int , but that's not what you're telling to printf . Hence, your expectations are not fulfilled.

A few things that are going on:

'printf' does not have any binary format specifier, so you would have to do it manually.

You need to take a deep dive in data types and their ranges, so I recommend using this source: Microsoft Data Type Ranges. It says C++, it is irrelevant since it gives you a good idea of the ranges.

I know this is isn't you're entire code, but just understand there are somethings from what I'm seeing that is not defined, such as 'filename'.

In case someone mentions atoi() and itoa(), keep this in mind, theoretically you could use atoi() and itoa(), however just be mindful that atoi() and itoa() is a non-standard function which is supported by some compilers.

Lastly, why are you using 'unsigned short int', '*(&numToWrite)' and is there anymore from the program that you can show us?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM