Milodupipo
Milodupipo

Reputation: 61

fwrite binary data from a string

I would like to create a file and write "A" into it (ascii is 65 == 01000001). Strange fact, whatever the value of std::string binary, there is always writed the letter P in myfile.txt.

    std::string binary = "01000001";
    std::string file = "myfile.txt";
    FILE* f;
    f = fopen(file.c_str(), "wb");      
    fwrite(&binary, 1, 1, f);     
    fclose(f);

After execution of this code, I read binary data with the command xxd -b myfile and I get this :

00000000: 01010000

Do you see a problem on this code ?

Upvotes: 1

Views: 3050

Answers (2)

cpatricio
cpatricio

Reputation: 457

Strings are bad when you want to do a bitstream...

int8_t binary = 0b01000001;
std::string file = "myfile.txt";
FILE* f;
f = fopen(file.c_str(), "wb");      
fwrite(&binary, 1, 1, f);     
fclose(f);

But when you are using C++, you don't really need to use C libraries

#include <fstream>

int main()
{
    std::fstream f;
    std::string file = "myfile.txt";
    f.open(file, std::fstream::out | std::fstream::binary);
    int8_t binary = 0b01000001; // int8_t is required to only write 8 bits/1 byte
    f << binary;
    f.close();
    return 0;
}

Upvotes: 2

Hatted Rooster
Hatted Rooster

Reputation: 36463

fwrite(&binary, 1, 1, f);

You pass a pointer of the std::string to fwrite, that's bad.

You will want to get a pointer to the internal buffer of the string by calling c_str():

fwrite(binary.c_str(), 1, 1, f);  

This is another reason to not use C file handles, fwrite's first argument is a const void* which is why your compiler didn't give you an error in the first place.

Upvotes: 6

Related Questions