confucious
confucious

Reputation:

What's a binary file and how do I create one?

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?

Upvotes: 5

Views: 69733

Answers (4)

paxdiablo
paxdiablo

Reputation: 881403

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

Upvotes: 18

Gishu
Gishu

Reputation: 136613

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

Upvotes: 3

anon
anon

Reputation:

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" );

Upvotes: 4

qrdl
qrdl

Reputation: 34968

See man for syscalls open, write and read.

Upvotes: 2

Related Questions