Search code examples
c++windowsfwrite

fwrite() doesn't write the full string


fwrite only writes 8 bytes, The file should contain "Hello, World!" however when I open it, it shows "Hello, W"

FILE* f = fopen("file.txt", "w");
const char* b = "Hello, World!\n";
fwrite(b, sizeof(char), sizeof(b), f);
fclose(f);

I've googled "fwrite doesn't write the full string" but I couldn't find something similar to my problem.


Solution

  • sizeof(b) returns the size of the pointer, not the length of the string. You could use strlen to get it though:

    fwrite(b, sizeof(char), strlen(b), f);
    // Here ----------------^