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

问题描述 投票:0回答:1

我正在尝试一种方法来操纵计算机中任何文件的二进制代码,以在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转换的那些字节,换句话说,我想将所有文件作为二进制文件而不是里面的内容

c++ binary compression fstream
1个回答
2
投票

<<对于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>才能使流格式操纵器hexfillsetw起作用。

请注意,setw仅在流中设置用于下一个输出操作,而hexfill将被设置,直到以其他方式明确设置为止。就是说,您只需要设置这两个操纵器一次,可能在循环之外。然后,完成后,可以将其设置为:

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

请参阅https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2以获取operator<<char数组的重载char函数的列表。

© www.soinside.com 2019 - 2024. All rights reserved.