1

我的目标是将文件写入磁盘

如果我使用 gio 创建文件

GError *error;
char path[strlen(dirpath)]; 
sprintf(path, "%s", dirpath); // Create path to the file by copying from another variable
zip_file_t *contentfile = zip_fopen_index(book, index, ZIP_RDONLY);
zip_stat_index(book, index, ZIP_CHECKCONS, &fileinfo);
GFile *gfile = g_file_new_for_path(strcat(path, fileinfo.name));
GFileOutputStream *file = g_file_create(gfile, G_FILE_CREATE_NONE, g_cancellable_new(), &error);
if (error)
    printf("Error :%i\n", error->code);
else
    zip_fread(contentfile, file, fileinfo.size);
g_error_free(error);

我不能在文件中放任何东西。它只是一个用 0 字节创建的文件。我正在使用 loo 提取存档中的所有文件。因此索引zip_file_t *contentfile = zip_fopen_index(book, index, ZIP_RDONLY);. 我收到一个段错误:GError 设置在先前 GError 或未初始化内存的顶部。

如果我使用文件

char path[strlen(dirpath)]; 
sprintf(path, "%s", dirpath); // Create path to the file by copying from another variable
zip_file_t *contentfile = zip_fopen_index(book, index, ZIP_RDONLY);
zip_stat_index(book, index, ZIP_CHECKCONS, &fileinfo);
FILE *file = fopen(strcat(path, fileinfo.name), "wb");
zip_fread(contentfile, file, fileinfo.size);

这给出了一个分段错误:double free or corruption (out)

如何正确地将 zip_read( 内容写入磁盘上的文件?

4

1 回答 1

0

@MikeCAT 是对的,我首先需要修复我的 char 路径大小。使用相同的想法,我将我void *buffer的改为char buffer[size]而不是指针。它确实从某些 zip 中保存文件,有些仍然给出分段错误。我将调查为什么[可能某处内存不足],但至少它现在确实有效。我稍后会更新

必须使用 malloc 设置缓冲区以避免错误,现在它可以工作了

static void extract_book(zip_t *book, char *bookname)
{
    int size = strlen(pubdir) + strlen(bookname) + 1;
    char pubpath[size];
    strncat(strncat(strcpy(pubpath, pubdir), bookname, strlen(bookname)), "/", 2);
    GFile *dir = g_file_new_for_path(pubpath);
    g_file_make_directory_with_parents(dir, NULL, NULL);
    for (int index = 0; index < zip_get_num_files(book); index++)
    {
        zip_file_t *contentfile = zip_fopen_index(book, index, 0);
        zip_stat_t fileinfo;
        int status = zip_stat_index(book, index, ZIP_FL_ENC_GUESS, &fileinfo);
        if (status == 0)
        {
            char *buffer = malloc(fileinfo.size);
            char filepath[size + strlen(fileinfo.name)];
            strcat(strcpy(filepath, pubpath), fileinfo.name);
            zip_fread(contentfile, buffer, fileinfo.size);
            zip_fclose(contentfile);
            FILE *file = fopen(filepath, "wb");
            fwrite(buffer, fileinfo.size, 1, file);
            fclose(file);
        }
        else
        {
            printf("%s at %i\n", puberror, zip_get_error(book)->zip_err);
        }
    }
}
于 2020-09-04T16:26:32.433 回答