Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write to file in binary in C?

Tags:

c

file-io

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;
}
like image 204
Ninja Avatar asked Nov 26 '25 15:11

Ninja


2 Answers

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);
like image 123
kennytm Avatar answered Nov 29 '25 10:11

kennytm


Use fwrite instead of fputs.

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

like image 33
Pablo Santa Cruz Avatar answered Nov 29 '25 10:11

Pablo Santa Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!