下面的问题和本文很可能是一个意思:
- How to read memory using file handler?
- How to read string as file?
有的C语言API只接受文件句柄作为参数。这时我们要处理的数据又已经在内存中了。那么怎样用文件句柄来操作这块数据呢?
比如zlib 中的 gzip File Access Functions 。
ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
它只有两种形式,或者直接打开一个文件,或者打开一个文件描述符。这时如果想处理已经存在于内存中的数据,就需要些别的处理方式了。
借助临时文件
FILE * tFile = tmpfile ();
fwrite(bytes, 1 , length , tFile);
fseek(tFile , 0 , SEEK_SET );
gzFile gzfile = gzdopen(fileno(tFile),"rb");
// gzip related operation
gzclose(tFile);
借助libc的函数
The GNU C Library 中的 String Streams 提供了下面两个函数:
FILE * fmemopen (void *buf, size_t size, const char *opentype);
FILE * open_memstream (char **ptr, size_t *sizeloc);