views:

442

answers:

4

I would like to create a binary file representing an integer. I think the file should be 4 bytes. I use linux. How to do that? Another question: How do I assign the content of that file to an integer in C?

+1  A: 

Open the file for binary read/write. fopen takes a b switch for file access mode parameter - see here

See the fopen page in Wikipedia for the difference between text and binary files as well as a code sample for writing data to a binary file

Gishu
+8  A: 

In standard C, fopen() allows the mode "wb" to write (and "rb" to read) in binary mode, thus:

#include <stdio.h>

int main() {
    /* Create the file */
    int x = 1;
    FILE *fh = fopen ("file.bin", "wb");
    if (fh != NULL) {
        fwrite (&x, sizeof (x), 1, fh);
        fclose (fh);
    }

    /* Read the file back in */
    x = 7;
    fh = fopen ("file.bin", "rb");
    if (fh != NULL) {
        fread (&x, sizeof (x), 1, fh);
        fclose (fh);
    }

    /* Check that it worked */
    printf ("Value is: %d\n", x);

    return 0;
}

This outputs:

Value is: 1
paxdiablo
keep this in mind (via man fopen): The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)
tr9sh
+1  A: 

See man for syscalls open, write and read.

qrdl
+2  A: 

From the operating system's point of view, all files are binary files. C (and C++) provide a special "text mode" that does stuff like expanding newline characters to newline/carriage-return pairs (on Windows), but the OS doesn't know about this.

In a C program, to create a file without this special treatment, use the "b" flag of fopen():

FILE * f = fopen("somefile", "wb" );
anon