0

I'm using libzip to extract the content of each file in a zip into my own data structure, a C++ immutable POD.

The problem is that every time I extract the content of a file, I get some random data with tacked on to the end. Here's my code:

void Parser::populateFileMetadata() {
int error = 0;
zip *zip = zip_open(this->file_path.c_str(), 0, &error);
if (zip == nullptr) {
  LOG(DEBUG)<< "Could not open zip file.";
  return;
}

const zip_int64_t n_entries = zip_get_num_entries(zip, ZIP_FL_UNCHANGED);
for (zip_int64_t i = 0; i < n_entries; i++) {
  const char *file_name = zip_get_name(zip, i, ZIP_FL_ENC_GUESS);
  struct zip_stat st;
  zip_stat_init(&st);
  zip_stat(zip, file_name, (ZIP_FL_NOCASE|ZIP_FL_UNCHANGED), &st);
  char *content = new char[st.size];
  zip_file *file = zip_fopen(zip, file_name, \
                             (ZIP_FL_NOCASE|ZIP_FL_UNCHANGED));
  const zip_int64_t did_read = zip_fread(file, content, st.size);
  if (did_read <= 0) {
    LOG(WARNING)<< "Could not read contents of " << file_name << ".";
    continue;
  }
  const FileMetadata metadata(string(file_name), -1, string(content));
  this->file_metadata.push_back(metadata);

  zip_fclose(file);
  delete[] content;
}
zip_close(zip);
}
4

2 回答 2

2

您正在构造一个 std::string ,content而没有告诉构造函数它有多长,因此构造函数将从缓冲区的开头读取,直到找到终止的 NUL。但是不能保证文件包含一个,因此构造函数会读取缓冲区的末尾,直到它碰巧找到一个 NUL。

修复:使用两个参数的 std::string 构造函数 ( string(const char* s, size_t size)) 并将数据长度传递给它。

于 2014-01-24T14:36:28.280 回答
1

zip_fread似乎增加了的大小content,所以我只是截断contentcontent[st.size] = '\0';

于 2014-01-24T16:12:21.530 回答