C:将字符数组(包含'1'和'0')写入文件中的二进制文件
C : Write char array (containing '1' and '0') into as binary in a file
我在将“1”和“0”的字符数组作为二进制文件写入文件时遇到问题。
这是我正在尝试做的一个例子:
int main(){
FILE * file;
file = fopen("file" , "w+b");
char buffer[8] = "11001100"; // 8 bits-> 1 byte to write
fwrite(buffer,1,8,file);
fclose(file);
return 0;
}
问题是它在我的文件中将自己写为文本(写入 8 个字节),而不是 binary/just 1 个字节。
我做错了什么?
在此先感谢您的帮助。
您必须将包含二进制数的ASCII 字符串转换为字节。你可以自己做,也可以简单地使用 strtol()
:
char *buffer = "11001100"; // 8 chars
char *behind;
char byte = (char)strtol(buffer, &behind, 2); // Base 2 for a binary number
fwrite(&byte,1,1,file); // 1 element with 1 byte ach
我认为您可以使用 0b
前缀...
GNU doc
0b
表示你正在写一个字节。
如果你这样写:
int main(){
FILE * file;
file = fopen("file" , "w+b");
char c;
c = 0b11001100
fwrite(&c,1,1,file);
fclose(file);
return 0;
}
我在将“1”和“0”的字符数组作为二进制文件写入文件时遇到问题。 这是我正在尝试做的一个例子:
int main(){
FILE * file;
file = fopen("file" , "w+b");
char buffer[8] = "11001100"; // 8 bits-> 1 byte to write
fwrite(buffer,1,8,file);
fclose(file);
return 0;
}
问题是它在我的文件中将自己写为文本(写入 8 个字节),而不是 binary/just 1 个字节。
我做错了什么?
在此先感谢您的帮助。
您必须将包含二进制数的ASCII 字符串转换为字节。你可以自己做,也可以简单地使用 strtol()
:
char *buffer = "11001100"; // 8 chars
char *behind;
char byte = (char)strtol(buffer, &behind, 2); // Base 2 for a binary number
fwrite(&byte,1,1,file); // 1 element with 1 byte ach
我认为您可以使用 0b
前缀...
GNU doc
0b
表示你正在写一个字节。
如果你这样写:
int main(){
FILE * file;
file = fopen("file" , "w+b");
char c;
c = 0b11001100
fwrite(&c,1,1,file);
fclose(file);
return 0;
}