解压到指定目录

libExtract to specified directory

本文关键字:      更新时间:2023-10-16

我有一个tar文件,我想用libchive解压到一个特定的目录。我怎样才能使libchive解压到我想要的任何目录?目前,它总是提取到我的程序的工作目录。我看了这个答案,但所有这一切都是改变存档中存档条目的位置,也就是说,它仍然提取到我的程序的工作目录,只是在不同的子目录。

我用下面的方法解决了这个问题:(在调用'archive_write_header'函数之前插入此代码)

    const char* currentFile = archive_entry_pathname(archiveEntry);
    const std::string fullOutputPath = destination + currentFile;
    archive_entry_set_pathname(archiveEntry, fullOutputPath.c_str());

,其中destination为输出路径。

来自图书馆讨论区:

"当然,这取决于要提取的归档文件。

通常,您将chdir()到您希望输出的目录,然后使用类似于Wiki示例页面中的代码:

一个完整的提取器示例

或在untar.c示例程序中:

解压示例

当然,如果要提取的tar文件有有趣的文件名(如"c:someotherdirectory")然后,您需要在提取时处理文件名。

注意所有的例子都使用了archive_read_next_header()从描述的输入存档中获取条目对象下一个条目;然后您可以自由编辑条目描述以任何你希望的方式——特别是,你可以改变名称、所有者或权限——在调用之前Archive_write_header()来重新创建条目磁盘。

上面Wiki中的示例页可能是

Alex的答案的较长C版本。要将文件解压缩到temp_dir,请使用archive_entry_pathname()archive_entry_set_pathname()重写每个条目::

char* dest_file;
for (;;) {
    r = archive_read_next_header(a, &entry);
    if (r == ARCHIVE_EOF)
      break;
    if (r < ARCHIVE_OK)
      fprintf(stderr, "%sn", archive_error_string(a));
    if (r < ARCHIVE_WARN)
      return NULL;
    asprintf(&dest_file, "%s/%s", temp_dir, archive_entry_pathname(entry));
    archive_entry_set_pathname(entry, dest_file);
    // printf(" writing %sn", dest_file);
    r = archive_write_header(ext, entry);
    if (r < ARCHIVE_OK)
      fprintf(stderr, "%sn", archive_error_string(ext));
    else if (archive_entry_size(entry) > 0) {
      r = copy_data(a, ext);
      if (r < ARCHIVE_OK)
        fprintf(stderr, "%sn", archive_error_string(ext));
      if (r < ARCHIVE_WARN)
        exit(1);
    }
    r = archive_write_finish_entry(ext);
    if (r < ARCHIVE_OK)
      fprintf(stderr, "%sn", archive_error_string(ext));
    if (r < ARCHIVE_WARN)
      return NULL;
    free(dest_file);
}
相关文章:
  • 没有找到相关文章