Can't write string of 1 and 0 to binary file, C++ -
i have function receives pointer string name of file open , code 1 , 0; codedline contains 010100110101110101010011 after writing binary file have same...would recommend? thank you.
void codefile(char *s) { char *buf = new char[maxstringlength]; std::ifstream filetocode(s); std::ofstream codedfile("codedfile.txt", std::ios::binary); if (!filetocode.is_open()) return; while (filetocode.getline(buf, maxstringlength)) { std::string codedline = codeline(buf); codedfile.write(codedline.c_str(), codedline.size()); } codedfile.close(); filetocode.close(); }
after writing binary file have same...
i suppose want convert std::string
input binary equivalent.
you can use std::bitset<>
class convert strings binary values , vice versa. writing string directly file results in binary representations of character values '0'
, '1'
.
an example how use it:
std::string zeroes_and_ones = "1011100001111010010"; // define bitset can hold sizeof(unsigned long) bits std::bitset<sizeof(unsigned long) * 8> bits(zeroes_and_ones); unsigned long binary_value = bits.to_ulong(); // write binary value file codedfile.write((const char*)&binary_value, sizeof(unsigned long));
note
above sample works c++11 standards. earlier version std::bitset
can't initialized directly string. can filled using operator>>()
, std::istringstream
example.
Comments
Post a Comment