Eugene
Eugene

Reputation: 307

Can't write string of 1 and 0 to binary file, C++

I have the function that receives a pointer to a string with a name of file to open and to code with 1 and 0; codedLine contains something like 010100110101110101010011 After writing to binary file I have exactly the same...Would would you 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();
}

Upvotes: 1

Views: 1454

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

After writing to binary file I have exactly the same...

I suppose you want to convert the std::string input to its binary equivalent.

You can use the std::bitset<> class to convert strings to binary values and vice versa. Writing the string directly to the file results in binary representations of the character values '0' and '1'.

An example how to use it:

std::string zeroes_and_ones = "1011100001111010010";
// Define a bitset that can hold sizeof(unsigned long) bits
std::bitset<sizeof(unsigned long) * 8> bits(zeroes_and_ones);

unsigned long binary_value = bits.to_ulong();

// write the binary value to file
codedFile.write((const char*)&binary_value, sizeof(unsigned long));

NOTE
The above sample works with standards. For earlier version the std::bitset can't be initialized directly from the string. But it can be filled using the operator>>() and std::istringstream for example.

Upvotes: 1

Related Questions