【问题标题】:Reading any file as binary in C++?在 C++ 中将任何文件作为二进制文件读取?
【发布时间】:2017-10-05 15:15:23
【问题描述】:

如何在 C++ 中将任何文件类型读取为二进制文件?到目前为止,我已经能够使用std::bitset 读取二进制文件中的 .txt 文件,如下所示:

std::ifstream myfile;
myfile.open("example.txt", std::ios::binary);
while (getline (myfile, line) ) {
    for (std::size_t i = 0; i<line.size(); ++i) {
        std::bitset<8> a = std::bitset<8>(line[i]); //convert every character to binary, save it in a

        std::cout<<((char)std::bitset<8>(a).to_ulong())<<'\n';
    }
}

在第一行中,我如何将sound.mp3word.docx 之类的文件作为二进制文件读取?我知道它们实际上只是二进制文件,但是我怎样才能读取它们呢?

谢谢!

【问题讨论】:

  • 这是一个计算机程序。所有文件都是二进制文件...
  • 在 C++ 标准库中查找“转换”。 cplusplus.com/reference/algorithm/transform/?kw=transform
  • @fredrik 我该如何阅读它们?
  • 您可以使用read 从二进制文件读取内存块,然后将每个字符转换为位。
  • @GiliL。可以举个例子吗?

标签: c++ file stream ifstream


【解决方案1】:

通过将字符的内存块转换为二进制,您可以将文件读取为二进制。

std::streampos size;
char * memblock;

std::ifstream myfile ("sound.mp3", std::ios::in|std::ios::binary|std::ios::ate);
//ios::ate puts the reader at the end of the file
if (file.is_open())
{
    size = myfile.tellg();
    memblockChar = new char [size];
    myfile.seekg (0, std::ios::beg);
    myfile.read (memblockChar, size);
    myfile.close();

    for (int i = 0; i<size; i++) {
        std::cout << (((std::bitset<8>)memblockChar[i]).to_ulong()) << '\n';
    }
    delete[] memblockChar;
}
else std::cout<<"Unable to open file"<<std::endl;

这可以在 main 方法中使用,也可以在其他任何地方使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2011-09-03
    • 2016-01-15
    相关资源
    最近更新 更多