读取C 中的二进制文件的任何文件

Reading any file as binary in C++?

本文关键字:任何 文件 二进制文件 读取      更新时间:2023-10-16

我如何读取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之类的文件读取为二进制文件?我了解它们实际上只是二进制文件,但是我该如何阅读它们?

谢谢!

通过从字符的存储器块铸造到二进制文件,您可以将文件读为二进制文件。

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;

这可以在主要方法或其他任何地方使用。