问题
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:
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
回答2:
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
回答4:
See man
for syscalls open
, write
and read
.
来源:https://stackoverflow.com/questions/979816/whats-a-binary-file-and-how-do-i-create-one