임시 파일을 만들지 않고 C에서 읽기를위한 gzipped 파일 열기

StackOverflow https://stackoverflow.com/questions/1820144

  •  10-07-2019
  •  | 
  •  

문제

Fopen과 FSCANF를 통해 C에서 읽고 싶은 파일이 있습니다. 어쨌든 파일을 임시 파일로 gunzip하지 않고도 할 수 있습니까?

감사.

도움이 되었습니까?

해결책

libzlib을 사용하여 Gziped 파일을 직접 열 수 있습니다.

또한 Fopen과 비슷하지만 Gzipped 파일에서 작동하는 "gzopen"기능을 제공합니다. 그러나 FSCANF는 일반 파일 포인터를 기대하기 때문에 그러한 핸들에서 작동하지 않을 것입니다.

다른 팁

만약에 popen 공정한 게임입니다 fopen 그리고 fscanf:

#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.]

사용하지 마세요

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

.gz 파일을 엽니 다. 대신 argv [1]를 제대로 탈출하십시오. 그렇지 않으면 취약점으로 끝날 수 있습니다.

123;rm -rf /

이미 위의 명령을 변경하는 데 도움이됩니다

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

' 0', '' ','; '와 같은 캐릭터를 피할 수도 있습니다. 등.

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;
}

당신이 사용할 수있는 zlib, 그러나 I/O 호출을 zlib에 따라 교체해야합니다.

이 작업을 수행하려면 파이프를 열어야합니다. 의사 코드의 기본 흐름은 다음과 같습니다.

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 이 작업을 수행하는 방법에 대한 자세한 내용은 주석의 페이지입니다.

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
}

사용하기가 아주 간단합니다 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;
}

연결하는 것을 잊지 마십시오 zlib, 유닉스 아래 gcc ... -lz

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top