gpt4 book ai didi

c++ - 将二进制文件(exe,zip等)读取为char *,c++

转载 作者:行者123 更新时间:2023-12-02 10:20:43 30 4
gpt4 key购买 nike

我正在尝试读取文件并将字节放入字节缓冲区中,但是当我尝试读取exe或zip文件时,并非所有字节都被加载到缓冲区中。我的功能:

char* read_file_bytes(const string &name) {
FILE *img = fopen(name.c_str(), "rb");
fseek(img, 0, SEEK_END);
unsigned long filesize = ftell(img);
char *buffer = (char*)malloc(sizeof(char)*filesize);
rewind(img);
fread(buffer, sizeof(char), filesize, img);
return buffer;
}

检查缓冲区的代码段:
char* bytes = read_file_bytes(path);
for(int i = 0; i < strlen(bytes); i++)
cout << hex << (unsigned int)(bytes[i]);

最佳答案

strlen()设计用于文本字符,而不用于二进制字节。当遇到nul char(0x00)(可能包含二进制数据)时,它将停止计数。

您的read_file_bytes()函数知道它读取了多少字节。您需要将该数字返回给调用方,例如:

typedef unsigned char byte;

byte* read_file_bytes(const std::string &name, unsigned long &filesize)
{
filesize = 0;

FILE *img = fopen(name.c_str(), "rb");
if (!img)
return NULL;

if (fseek(img, 0, SEEK_END) != 0)
{
fclose(img);
return NULL;
}

long size = ftell(img);
if (size == -1L)
{
fclose(img);
return NULL;
}

byte *buffer = static_cast<byte*>(std::malloc(size));
if (!buffer)
{
fclose(img);
return NULL;
}

rewind(img);
if (fread(buffer, 1, size, img) < size)
{
free(buffer);
close(img);
return NULL;
}

fclose(img);

filesize = size;
return buffer;
}

unsigned long filesize;
byte* bytes = read_file_bytes(path, filesize);

for(unsigned long i = 0; i < filesize; ++i)
std::cout << std::hex << static_cast<unsigned int>(bytes[i]);

free(bytes);

请注意,这种方法非常C式且容易出错。更多的C++方法看起来像这样:

using byte = unsigned char;
// or, use std::byte in C++17 and later...

std::vector<byte> read_file_bytes(const std::string &name)
{
std::ifstream img;
img.exceptions(std::ifstream::failbit | std::ifstream::badbit);
img.open(name.c_str(), std::ifstream::binary | std::ifstream::ate);

std::ifstream::pos_type size = img.tellg();
ifs.seekg(0, std::ios::beg);
// or, use std::filesystem::file_size() instead...

std::vector<byte> buffer(size);
img.read(buffer.data(), size);

return buffer;
}

std::vector<byte> bytes = read_file_bytes(path);
for(byte b : bytes)
std::cout << std::hex << static_cast<unsigned int>(b);

关于c++ - 将二进制文件(exe,zip等)读取为char *,c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60353065/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com