我正在尝试一种方法来操纵计算机中任何文件的二进制代码,以在c ++中应用压缩/解压缩算法。我已经搜索了很长时间,发现的所有内容都是如何读取.bin文件:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
streampos size;
char * memblock;
ifstream file ("name.bin", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char[size];
file.seekg (0, ios::beg);
file.read (memblock, size);
for(int i = 0 ; i < size ; i++){
cout << memblock[i] ;
}
file.close();
cout << "\n\n the entire file content is in memory";
delete[] memblock;
}
else cout << "Unable to open file";
return 0;
}
我只想不使用ASCII转换的那些字节,换句话说,我想将所有文件作为二进制文件而不是里面的内容
<<
对于char
类型过载,以输出ASCII格式的字符。 memblock
数组中的数据(一和零)将作为二进制正确读取。只是显示它们的方式就是ASCII。代替char[]
的memblock
,将其设为uint8_t[]
。然后,当您输出时,请执行
std::cout << std::hex << std::fill('0') << std::setw(2) << memblock[i];
^ ^ ^
| | |
| | sets the width of the next output
| sets the fill character (default is space)
tells the stream to output all numbers in hexadecimal
您必须#include <iomanip>
才能使流格式操纵器hex
,fill
和setw
起作用。
请注意,setw
仅在流中设置用于下一个输出操作,而hex
和fill
将被设置,直到以其他方式明确设置为止。就是说,您只需要设置这两个操纵器一次,可能在循环之外。然后,完成后,可以将其设置为:
std::cout << std::dec << std::fill(' ');
请参阅https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2以获取operator<<
和char
数组的重载char
函数的列表。