简体   繁体   English

如何在C中以二进制形式写入文件?

[英]How do I write to file in binary in C?

Why does this code not work as expected? 为什么此代码无法按预期工作?

#include <cstdio>
    int main()
{
char mona[] =       
                   "\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x01\x90"
                   "\x00\x00\x02\x5d\x01\x03\x00\x00\x00\x26\xef\xb3\x78\x00\x00\x00\x45\x74\x45\x58"
   // <snip>
                   "\x00\x49\x45\x4e\x44\xae\x42\x60\x82";
FILE *fp = fopen("mona.png","wb");
fputs(mona,fp);
fclose(fp);
return 0;
}

fputs is supposed to write a null-terminated string. fputs应该写一个以空值结尾的字符串。 It will stop once a '\\0' is detected. 一旦检测到'\\0' ,它将停止。 You should use fwrite to write binary data. 您应该使用fwrite写入二进制数据。

  fwrite(mona, 1, sizeof(mona), fp);

Use fwrite instead of fputs . 使用fwrite代替fputs

fputs is for writing character (not binary) data to files. fputs用于将字符(不是二进制)数据写入文件。

You must use fwrite AND the binary flag on fopen, like 您必须在fopen上使用fwrite AND二进制标志,例如

fopen("blah.bin","wb");

If you dont use "b", all your file-operations will work in text-modus (standard) also with fwrite. 如果您不使用“ b”,则所有文件操作都将与fwrite一起以文本模式(标准)工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM