2017-05-07 45 views
-1

如何在C++中将任何文件类型读为二进制文件?到目前为止,我已经能够读取.TXT使用std::bitset二进制文件,像这样:在C++中以二进制形式读取任何文件?

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作为一个二进制文件的文件?我明白,他们真的只是二进制文件,但我怎样才能阅读它们?

谢谢!

+5

这是一个计算机程序。所有文件都是二进制文件... – fredrik

+1

在C++标准库中查找“变换”。 http://www.cplusplus.com/reference/algorithm/transform/?kw=transform – NonCreature0714

+0

@fredrik我如何阅读它们? –

回答

0

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

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; 

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