将文本文件转换为二进制文件,然后返回文本

时间:2015-10-03 19:09:25

标签: c++

我正在尝试将文本文件转换为二进制文件,然后读入该二进制文件并将其转换回文本。这是我为它写的代码,但是中间文件,即二进制文件"ex7_out1",也是文本,我期待文本的二进制编码形式,这是怎么发生的?

#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; }

}

输入文件"ex7_in"包含一行文本。 这是Bjarne Stroustrup的书“Programming:Principles and Practice Using C ++”的练习。

1 个答案:

答案 0 :(得分:1)

可以使用std::bitset完成此操作。

格式

文本:

ABCD

二进制代表文本:

0010000
0010001
0010010
0010011

转换

从文字到二进制:

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>

从二进制到文字:

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());

这适用于文本模式流。你想读它。我们不读二进制文件,除非我们使用HEX编辑器为我们阅读,这与我上面做的一样。

相关问题