Reputation: 1128
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
Reputation: 19607
This can be done with std::bitset
.
text:
ABCD
binary-representing text:
0010000
0010001
0010010
0010011
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