gpt4 book ai didi

c - 读取一个 char 字符串作为一个虚拟文件

转载 作者:行者123 更新时间:2023-12-02 22:19:25 25 4
gpt4 key购买 nike

这个问题可能看起来很奇怪,但我没有拼错:我想解压缩我下载的一些数据而不将它们写入硬盘。为此,我将它下载到一个动态分配的缓冲区中,我想将它发送到我使用的 zlib 包装器 (miniunzip)。问题是这个实现很长(2-3K 行),我想避免只为几行重写它。我想知道是否有任何方法可以通过 FILE* 结构读取缓冲区(miniunzip 使用它自己的结构,但我发现加载程序下隐藏了一个“fopen()”)。如果有帮助,我知道它的长度。

提前致谢,请原谅我糟糕的语法。

我在 Windows 和 UNIX 系统 (OSX/GNU Linux) 上工作。

最佳答案

如果您谈论的是包含在 zlib 中的 minizip 库,您可以使用 unzOpen2 函数,它允许您指定包含要使用的 I/O 函数的结构。这应该让你开始:

struct zmem_data {
char *buf;
size_t length;
};

static voidpf zmemopen(voidpf opaque, const char *filename, int mode) {
if ((mode&ZLIB_FILEFUNC_MODE_READWRITEFILTER) != ZLIB_FILEFUNC_MODE_READ) return NULL;
uLong *pos = malloc(sizeof(uLong));
*pos = 0;
return pos;
}

static uLong zmemread(voidpf opaque, voidpf stream, void* buf, uLong size) {
struct zmem_data *data = (struct zmem_data*)opaque;
uLong *pos = (uLong*)stream;
uLong remaining = data->length - *pos;
uLong readlength = size < remaining ? size : remaining;
if (*pos > data->length) return 0;
memcpy(buf, data->buf+*pos, readlength);
*pos += readlength;
return readlength;
}

static uLong zmemwrite(voidpf opaque, voidpf stream, const void *buf, uLong size) {
/* no write support for now */
return 0;
}

static int zmemclose(voidpf opaque, voidpf stream) {
free(stream);
return 0;
}

static int zmemerror(voidpf opaque, voidpf stream) {
if (stream == NULL) return 1;
else return 0;
}

static long zmemtell(voidpf opaque, voidpf stream) {
return *(uLong*)stream;
}

static long zmemseek(voidpf opaque, voidpf stream, uLong offset, int origin) {
struct zmem_data *data = (struct zmem_data*)opaque;
uLong *pos = (uLong*)stream;
switch (origin) {
case ZLIB_FILEFUNC_SEEK_SET:
*pos = offset;
break;
case ZLIB_FILEFUNC_SEEK_CUR:
*pos = *pos + offset;
break;
case ZLIB_FILEFUNC_SEEK_END:
*pos = data->length + offset;
break;
default:
return -1;
}
return 0;
}

static void init_zmemfile(zlib_filefunc_def *inst, char *buf, size_t length) {
struct zmem_data *data = malloc(sizeof(struct zmem_data));
data->buf = buf;
data->length = length;
inst->opaque = data;
inst->zopen_file = zmemopen;
inst->zread_file = zmemread;
inst->zwrite_file = zmemwrite;
inst->ztell_file = zmemtell;
inst->zseek_file = zmemseek;
inst->zclose_file = zmemclose;
inst->zerror_file = zmemerror;
}

static void destroy_zmemfile(zlib_filefunc_def *inst) {
free(inst->opaque);
inst->opaque = NULL;
}

void example() {
zlib_filefunc_dec fileops;
init_zmemfile(&fileops, buffer, buffer_length);
unzFile zf = unzOpen2(NULL, &fileops);
/* ... process zip file ... */
unzClose(zf);
destroy_zmemfile(&fileops);
}

关于c - 读取一个 char 字符串作为一个虚拟文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13961912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com