在C语言中打开gzip压缩文件进行读取而不创建临时文件

9
我有一些被压缩的文件,想要通过fopen和fscanf函数在C语言中读取它们。是否有办法在不需要将文件解压到临时文件的情况下做到这一点?
谢谢。
8个回答

8
你可以使用libzlib直接打开gzipped文件。
它还提供了一个“gzopen”函数,类似于fopen但操作gzipped文件。但是,fscanf可能无法在此类句柄上工作,因为它期望普通的FILE指针。

你可以使用 fdopen 函数将文件描述符作为 FILE 指针打开。 - Nathan Fellman
1
你必须在使用gzopen打开的文件上使用gzread——C语言无法提供足够的多态性以使库定义“自定义”文件描述符或FILE*句柄与POSIX或标准I/O函数一起工作。但我认为并没有gzscanf,所以你需要读入一个缓冲区并使用sscanf。 - Steve Jessop

6

如果可以使用popen,则可以使用fopenfscanf来完成:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[])
{
  const char prefix[] = "zcat ";
  const char *arg;
  char *cmd;
  FILE *in;
  char buf[4096];

  if (argc != 2) {
    fprintf(stderr, "Usage: %s file\n", argv[0]);
    return 1;
  }

  arg = argv[1];
  cmd = malloc(sizeof(prefix) + strlen(arg) + 1);
  if (!cmd) {
    fprintf(stderr, "%s: malloc: %s\n", argv[0], strerror(errno));
    return 1;
  }

  sprintf(cmd, "%s%s", prefix, arg);

  in = popen(cmd, "r");
  if (!in) {
    fprintf(stderr, "%s: popen: %s\n", argv[0], strerror(errno));
    return 1;
  }

  while (fscanf(in, "%s", buf) == 1)
    printf("%s: got [%s]\n", argv[0], buf);

  if (ferror(in)) {
    fprintf(stderr, "%s: fread: %s\n", argv[0], strerror(errno));
    return 1;
  }
  else if (!feof(in)) {
    fprintf(stderr, "%s: %s: unconsumed input\n", argv[0], argv[1]);
    return 1;
  }

  return 0;
}

例如:

$ zcat file.gz
Every good boy does fine.
$ ./gzread file.gz
./gzread: got [Every]
./gzread: got [good]
./gzread: got [boy]
./gzread: got [does]
./gzread: got [fine.]

5

请勿使用

sprintf(cmd, "zcat %s", argv[1]);
popen(cmd,"r");

打开 .gz 文件。请正确转义 argv[1],否则可能会出现漏洞,特别是当某些人注入参数 argv[1] 时。

123;rm -rf /

为了使以上指令更易理解,可以进行修改为

sprintf(cmd, "zcat \'%s\'",argv[1]);

您可能还需要转义像 '\0'、'\''、'\;' 等字符。


1

gzscanf()新手尝试:

#include <stdio.h>
#include <stdarg.h>
#include <zlib.h>

#define MAXLEN 256

int gzscanf(gzFile *stream, const char *fmt, ...) {
  /* read one line from stream (up to newline) and parse with sscanf */
  va_list args;
  va_start(args, fmt);
  int n;
  static char buf[MAXLEN]; 

  if (NULL == gzgets(stream, buf, MAXLEN)) {
    printf("gzscanf: Failed to read line from gz file.\n");
    exit(EXIT_FAILURE);
  }
  n = vsscanf(buf, fmt, args);
  va_end(args);
  return n;
}

1
你可以使用zlib并将其包装到常规文件指针中,这样你就可以透明地使用fscanf、fread等函数。
FILE *myfopen(const char *path, const char *mode)
{
#ifdef WITH_ZLIB
  gzFile *zfp;

  /* try gzopen */
  zfp = gzopen(path,mode);
  if (zfp == NULL)
    return fopen(path,mode);

  /* open file pointer */
  return funopen(zfp,
                 (int(*)(void*,char*,int))gzread,
                 (int(*)(void*,const char*,int))gzwrite,
                 (fpos_t(*)(void*,fpos_t,int))gzseek,
                 (int(*)(void*))gzclose);
#else
  return fopen(path,mode);
#endif
}

0

你必须打开一个管道来实现这个。伪代码中的基本流程是:

create pipe // man pipe

fork // man fork

if (parent) {
    close the writing end of the pipe // man 2 close
    read from the pipe // man 2 read
} else if (child) {
    close the reading end of the pipe // man 2 close
    overwrite the file descriptor for stdout with the writing end of the pipe // man dup2 
    call exec() with gzip and the relevant parameters // man 3 exec
}

您可以在注释中使用man页面了解更多有关如何执行此操作的详细信息。


0

你可以使用zlib,但这需要你将I/O调用更改为特定于zlib的。


您还需要minizip库。Zip中的压缩方式相同,但需要虚拟目录处理。 - Martin Beckett

0

使用zlib打开.gz文件非常简单。在zlib.net上有一个合理的手册。

以下是一个快速示例,帮助您入门:

#include <stdio.h>
#include <zlib.h>

int main( int argc, char **argv )
{
    // we're reading 2 text lines, and a binary blob from the given file
    char line1[1024];
    char line2[1024];
    int  blob[64];

    if (argc > 1)
    {
        const char *filename = argv[1];
        gzFile gz_in = gzopen( filename, "rb" );  // same as fopen()

        if (gz_in != NULL)
        {
            if ( gzgets( gz_in, line1, sizeof(line1) ) != NULL )  // same as fgets()
            {
                if ( gzgets( gz_in, line2, sizeof(line2) ) != NULL )
                {
                    if ( gzfread( blob, sizeof(int), 64, gz_in ) == 64 )  // same as fread()
                    {
                        printf("Line1: %s", line1);
                        printf("Line2: %s", line2);
                        // ...etc
                    }
                }
            }
            gzclose(gz_in);  // same as fclose()
        }
        else
        {
            printf( "Failed to GZ-open [%s]\n", filename );
        }
    }
    return 0;
}

记得在UNIX下使用gcc ... -lz链接zlib


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接