这可能以前已经回答过,但我尝试了几种方法都没有成功。
我需要的是读取 C++ 中任何文件类型的所有字节并访问每个字节的十进制值。
Eg
some_file.txt
ab¶
Expected outcome of each byte would be (in binary):
01100001 01100010 11110100
Final result as a decimal (NEED THIS):
97 98 244
some_file.bin
01000001 01000010 11110100
Would have to read the 8 bits of each byte and return each value in decimal (NEED THIS)
65 66 244
-
出于好奇,我需要小数来访问按照 ASCII 表组装的堆的位置,以计算每个字符的出现次数。
编辑 - 我有以下代码来读取任何类型的文件:
readFile.cpp
char* mem;
void readFile(char* file_name)
{
ifstream::pos_type size;
ifstream file;
file.open(file_name, ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
mem = new char[size];
file.seekg(0, ios::beg);
file.read(mem, size);
file.close();
delete[] mem;
}else{
cout << "Not able to open the file";
}
}
main.cpp
if(argc != 2) {
exit(1);
}
char* fileName = argv[1];
readFile(fileName);
cout << mem[0] << " | dec: " << (int) (unsigned char) mem[0] << endl;
cout << mem[1] << " | dec: " << (int) (unsigned char) mem[1] << endl;
cout << mem[2] << " | dec: " << (int) (unsigned char) mem[2] << endl;
cout << mem[3] << " | dec: " << (int) (unsigned char) mem[3] << endl;
当输入文件类似于“abc”时,输出是正确的:
a | dec: 97
b | dec: 98
c | dec: 99
但是当输入包含一些扩展的 ASCII 字符时,输出会变得疯狂:
input = a¶aa
output =
a | dec: 97
\ | dec: 92
2 | dec: 50
6 | dec: 54