开发者

How do I write to file in binary in C?

开发者 https://www.devze.com 2023-01-18 08:14 出处:网络
Why does this code not work as expected? #include开发者_JS百科 <cstdio> int main() { char mona[] =

Why does this code not work as expected?

#include开发者_JS百科 <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. It will stop once a '\0' is detected. You should use fwrite to write binary data.

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


Use fwrite instead of fputs.

fputs is for writing character (not binary) data to files.


You must use fwrite AND the binary flag on fopen, like

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

If you dont use "b", all your file-operations will work in text-modus (standard) also with fwrite.

0

精彩评论

暂无评论...
验证码 换一张
取 消