Effective_cellist
Effective_cellist

Reputation: 1128

Converting text file to binary, and back to text

I am trying to convert a text file to binary, then read in that binary file and convert it back to text. This is the code I wrote for it,but the intermediate file, i.e. the binary file,"ex7_out1", is also in text,I was expecting binary encoded form of the text, how does this happen?

#include "std_lib_facilities.h"

int main()
{
    //to binary from text
    ifstream ifs{"ex7_in", ios_base::binary};
    ofstream ofs{"ex7_out1", ios_base::binary};
    char ch;
    while(ifs.get(ch)) { ofs.write(as_bytes(ch),sizeof(char)); }

    ifs.close();
    ofs.close();

    //from binary to text
    ifstream ifs1{"ex7_out1", ios_base::binary};
    ofstream ofs1{"ex7_out2"};
    char ch1;
    while(ifs1.read(as_bytes(ch1), sizeof(char))) { ofs1 << ch1; }

}

The input file "ex7_in" contains one line of text. This is an excercise from Bjarne Stroustrup's book,Programming:Principles and Practice Using C++.

Upvotes: 0

Views: 3372

Answers (1)

LogicStuff
LogicStuff

Reputation: 19607

This can be done with std::bitset.

Format

text:

ABCD

binary-representing text:

0010000
0010001
0010010
0010011

Conversion

From text to binary:

for(auto it = std::istream_iterator<char>(ifs1); it != std::istream_iterator<char>(); ++it)
    ofs1 << std::bitset<CHAR_BIT>(*it) << std::endl; // CHAR_BIT is defined in <climits>

From binary to text:

for(auto it = std::istream_iterator<std::string>(ifs); it != std::istream_iterator<std::string>(); ++it)
    ofs << static_cast<char>(std::bitset<CHAR_BIT>(*it).to_ulong());

This is meant to be used with text-mode streams. You want to read it. We don't read binary, unless we use HEX editor to read it for us, which is the same thing I did above.

Upvotes: 1

Related Questions