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 ?
fopen(file.c_str()..., but didfwrite(&binary.... One of them is wrong.binaryvariable is a string that contains the ASCII representation of "01000001". This is not a number is TEXT. To write "A" into the file you should usebinary = "A"and then `fwrite(binary.c_str(),1,1,f)!!! But I think you would convert binary in its ASCII value starting from the binary value.#include <iostream> #include <cstdio> #include <cstdlib> int main(void) { std::string binary = "01000001"; std::string file = "myfile.txt"; char c; FILE* f; c=strtol(binary.c_str(), NULL, 2); f = fopen(file.c_str(), "wb"); // fwrite(binary.c_str(),1, 1, f); fwrite(&c,1, 1, f); fclose(f); return 0; }... You shall insert the right indentation!std::stringisn't the best way to do that. Do you have suggestions to do that without strings ?