使用libarchive重命名存档中的非空目录

Rename a non-empty directory in an archive using libarchive

本文关键字:libarchive 重命名 使用      更新时间:2023-10-16

我正在尝试使用libarchive库重命名存档的条目。我特别使用函数archive_entry_set_pathname

文件和空目录被正确重命名,但不幸的是,如果目录不是空的,这就不起作用:一个新的目录没有被重命名,而是被创建为具有旧名称的目标目录的同级目录。

相关代码片段:

...
while (archive_read_next_header(inputArchive, &entry) == ARCHIVE_OK) {
        if (file == QFile::decodeName(archive_entry_pathname(entry))) {
            // FIXME: not working with non-empty directories
            archive_entry_set_pathname(entry, QFile::encodeName(newPath));    
        }
        int header_response;
        if ((header_response = archive_write_header(outputArchive, entry)) == ARCHIVE_OK) {
            ... // write the (new) outputArchive on disk
        }
    }

非空目录有什么问题?

在归档中,文件存储时使用相对于归档根的完整路径名。您的代码只匹配目录条目,还需要匹配该目录下的所有条目并重命名它们。我不是Qt专家,我还没有尝试过这个代码,但你会明白的。

QStringLiteral oldPath("foo/");
QStringLiteral newPath("bar/");
while (archive_read_next_header(inputArchive, &entry) == ARCHIVE_OK) {
    QString arEntryPath = QFile::decodeName(archive_entry_pathname(entry));
    if(arEntryPath.startsWith(oldPath) {
        arEntryPath.replace(0, oldPath.length(), newPath);
        archive_entry_set_pathname(entry, QFile::encodeName(arEntryPath));
    }
    int header_response;
    if ((header_response = archive_write_header(outputArchive, entry)) == ARCHIVE_OK) {
        ... // write the (new) outputArchive on disk
    }
}