如何从libzip保存二进制文件

问题描述

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

如果我使用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,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,ZIP_RDONLY);中的索引。我遇到了段错误:在先前的GError或未初始化的内存上方设置了GError。

如果我使用FILE

char path[strlen(dirpath)]; 
sprintf(path,&fileinfo);
FILE *file = fopen(strcat(path,fileinfo.name),"wb");
zip_fread(contentfile,fileinfo.size);

这会产生分段错误:两次释放或损坏(出)

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

解决方法

@MikeCAT是正确的,我首先需要修复字符路径的大小。使用相同的想法,我将void *buffer更改为char buffer[size],而不是指针。它确实从某些zip中保存文件,而某些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,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);
        }
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...