我目前正在尝试以十六进制值的形式读取文件,就像十六进制编辑器一样。为了解释这个问题,让我们假设我有一个test.txt,里面有一个简单的"Hello world“。我试图用接近以下代码的程序读取十六进制。
#include <iostream>
#include <fstream>
int main(int argc, char* argv[]) {
std::ifstream stream;
stream.open("test.txt", std::ios_base::binary);
if (!stream.bad()) {
std::cout << std::hex;
std::cout.width(2);
while (!stream.eof()) {
unsigned char c;
stream >> c;
std::cout << static_cast<unsigned>(c) << " ";
}
}
return 0;
}作为终端的输出
nux@pc-lubuntu:~/repos/readingHex$ od -x test.txt
0000000 6548 6c6c 206f 6f77 6c72 0a64
0000014
nux@pc-lubuntu:~/repos/readingHex$ ./a.out
48 65 6c 6c 6f 77 6f 72 6c 64 64显然,这是有区别的,但这应该是很容易纠正的。但是,正如您在输出日志上看到的那样,结果在字节5-6和9-10时是不同的。有人想办法解决这个问题吗?
谢谢。
发布于 2020-07-04 22:00:39
将此更改为:
while (!stream.eof()) {
unsigned char c;
stream >> c;
std::cout << static_cast<unsigned>(c) << " ";
}这是:
unsigned char c{};
stream >> std::noskipws;
while (stream >> c) {
std::cout << static_cast<unsigned>(c) << " ";
}std::noskipws禁止跳过空白。while (!stream.eof())或者,您也可以使用朗读:
stream.seekg(0, stream.end);
int length = stream.tellg();
stream.seekg(0, stream.beg);
std::vector<char> buffer(length);
stream.read(&buffer[0], length);
for (auto c : buffer) {
std::cout << static_cast<unsigned>(c) << " ";
}https://stackoverflow.com/questions/62734135
复制相似问题