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?
Asked
Active
Viewed 6.2k times
4 Answers
16
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
- 854,327
- 234
- 1,573
- 1,953
-
2keep 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.) – Jun 11 '09 at 13:45
-
for `float` use this one: https://stackoverflow.com/a/4465303 – gabor aron Oct 27 '21 at 11:31
4
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" );
3
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
- 134,492
- 47
- 225
- 308