如何以二进制形式读取任何类型的文件并使用 C++ 根据需要对其进行编辑(如压缩)?

How to read any kind of files as binary and edit it as you want (like compress it) with c++?

我想找出一种方法来操作计算机中任何文件的二进制代码,目的是在 c++ 中应用 compress/decompress 算法。 我已经搜索了很长时间,我发现的只是如何读取 .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 数组中的数据(1 和 0)以二进制形式准确读入。这就是您显示它们的方式,即 ASCII。将 memblock 改为 char[],改为 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> 流格式操纵器 hexfillsetw 才能工作。

请注意,setw 只会在下一次输出操作的流上设置,而 hexfill 将一直设置,直到明确设置为止。也就是说,您只需要设置这两个操纵器一次,可能在您的循环之外。然后当你完成后,你可以像这样将它们设置回去:

std::cout << std::dec << std::fill(' ');

有关 charchar 数组的重载 operator<< 函数列表,请参阅 https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2

答案比我们想象的要简单:

包含位集

for(int i = 0 ; i < size ; i++){

//changing the value of "memblock[i]" to binary byte per byte with for loop
//and of course using bitset

bitset<8> test (memblock[i]);
cout << test ;

}