libzip zip_fread on image停止在空字节-损坏的图像- c++



当尝试使用libzip解压缩图像文件时,我遇到了这样的问题:在图像数据中,我遇到了一个空字节,libzip zip_fread将此视为EOF并停止读取文件,导致图像损坏。在读取图像并提取完整图像时,处理空字节的最佳方法是什么?

需要说明的是,纯文本文件的提取效果非常好。

下面的代码:

int FileHandler::ExtractFiles(std::string& path, std::string& file, bool is_test)
{
int err = 0;
std::string fullPath = path + "\" + file;
zip* za = zip_open(fullPath.c_str(), 0, &err);
struct zip_stat st;
zip_stat_init(&st);
int number_of_entries = zip_get_num_entries(za, NULL);
for (zip_uint64_t i = 0; i < number_of_entries; ++i)
{
const char* name = zip_get_name(za, i, NULL);
std::string s_name = name;
size_t pos;
std::string backsl = "\";
while ((pos = s_name.find(47)) != std::string::npos)
{
s_name.replace(pos, 1, backsl);
}
std::string fullFilePath = path + "\" + s_name;
if(!is_test)
printf("Extracting: %s...n", s_name.c_str());
std::string fullDir;
size_t found;
found = fullFilePath.find_last_of("\");
if (found != std::string::npos)
{
fullDir = fullFilePath.substr(0, found);
}
struct zip_stat ist;
zip_stat_init(&ist);
zip_stat(za, name, 0, &ist);
char* contents = new char[ist.size];
zip_file* f = zip_fopen(za, name, 0);
// zip_fread to contents buffer
zip_fread(f, contents, ist.size);

if (CreateDirectory(fullDir.c_str(), NULL) || ERROR_ALREADY_EXISTS == GetLastError())
{
// writing buffer to file
if (!std::ofstream(fullFilePath).write(contents, ist.size))
{
return EXIT_FAILURE;
}
}
zip_fclose(f);
}
zip_close(za);
return EXIT_SUCCESS;
}

gerum为我指明了正确的方向。对于任何想知道或有相同问题的人,我不得不在二进制模式下打开ofstream并解决了这个问题。

原始代码:

// writing buffer to file
if (!std::ofstream(fullFilePath).write(contents, ist.size))
{
return EXIT_FAILURE;
}

解决方案:

// writing buffer to file
if (!std::ofstream(fullFilePath, std::ios::binary).write(contents, ist.size))
{
return EXIT_FAILURE;
}

最新更新