简体   繁体   中英

File handling in C - unexpected output

I am trying to figure out the output to the following code:

#include <stdio.h>

int main()
{
    FILE *f;
    int i = 20;
    if ((f = fopen("file.DAT", "wb")) != NULL) {
        fwrite(&i, 4, 1, f);
        fclose(f);
    }
    return 0;
}

On a 32-bit system, a paragraph sign (decimal ascii value 182 ) is written to binary file.

Question : How to determine which ascii value will be written to binary file?

First argument of function fwrite is a pointer to array, but array is not defined in the code. How to track which bytes are written to binary file?

This code writes the internal representation of the int i into the file file.DAT opened in binary mode. &i is not the address of an array, it is the address of local variable i . fwrite will write the 4 bytes at that address, which on a 32-bit system make up the integer in question.

On little endian architectures, such as Intel PCs and Macs, file should contain 4 bytes with values:

+---------------------------+
| 0x14 | 0x00 | 0x00 | 0x00 |
+---------------------------+

But on a big endian machine, such as the older Macs, the file contents would be:

+---------------------------+
| 0x00 | 0x00 | 0x00 | 0x14 |
+---------------------------+

If you print this file to the terminal or load it into an editor, you might see a funny character for the non-ASCII value 0x14 and other marks or none for the null bytes. This character shows as a paragraph sign, maybe because the editor performs some kind of character set conversion. Use a binary dump utility to see the exact contents of the file.

For more portability, the code should read fwrite(&i, sizeof i, 1, f);

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