Ninja
Ninja

Reputation: 21

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;
}

Upvotes: 2

Views: 8879

Answers (3)

user411313
user411313

Reputation: 3990

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.

Upvotes: 2

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

Use fwrite instead of fputs.

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

Upvotes: 3

kennytm
kennytm

Reputation: 523164

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);

Upvotes: 14

Related Questions