(c++) Read .dat file as hex using ifstream

旧城冷巷雨未停 提交于 2019-12-02 05:25:39

You should open the stream as binary, as mentioned. You can use the regular >> operator if you tell it not to skip white space.

unsigned char x;
std::ifstream input("00000000.dat", std::ios::binary);
input >> std::noskipws;
while (input >> x) {
    std::cout << std::hex << std::setw(2) << std::setfill('0')
              << (int)x;
}

To get the content into a string, you can use an ostringstream instead of cout.

You want to open the file to read as binary. You're reading as text right now. So it should look like

//Open file object to read as binary
std::ifstream input("00000000.dat", std::ios::in | std::ios::binary);    

You also might want to use reinterpret_cast to read one byte at a time (i.e. can't figure out what you want -- your code and your description are doing opposite things).

//Read until end of file
while(!input.eof())    
{

    //Or .good() if you're paranoid about using eof()

    //Read file one byte at a time
    input.read(reinterpret_cast<char *>(&h1), sizeof(unsigned char));

}

Or if you just want everything in one string, why not just declare a string and read it into that?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!