1. // linux下popen函数用法代码:zread.c,摘自gzip例子
  2. #include <stdio.h> 
  3. #include <stdlib.h> 
  4. #include <string.h> 
  5.  
  6. /* Trivial example of reading a gzip'ed file or gzip'ed standard input 
  7.  * using stdio functions fread(), getc(), etc... fseek() is not supported. 
  8.  * Modify according to your needs. You can easily construct the symmetric 
  9.  * zwrite program. 
  10.  * 
  11.  * Usage: zread [file[.gz]] 
  12.  * This programs assumes that gzip is somewhere in your path. 
  13.  */ 
  14. int main(argc, argv) 
  15.     int argc; 
  16.     char **argv; 
  17.     FILE *infile; 
  18.     char cmd[256]; 
  19.     char buf[BUFSIZ]; 
  20.     int n; 
  21.  
  22.     if (argc < 1 || argc > 2) { 
  23.         fprintf(stderr, "usage: %s [file[.gz]]\n", argv[0]); 
  24.         exit(EXIT_FAILURE); 
  25.     } 
  26.     strcpy(cmd, "gzip -dc ");  /* use "gzip -c" for zwrite */ 
  27.     if (argc == 2) { 
  28.         strncat(cmd, argv[1], sizeof(cmd)-strlen(cmd)); 
  29.     } 
  30.     infile = popen(cmd, "r");  /* use "w" for zwrite */ 
  31.     if (infile == NULL) { 
  32.         fprintf(stderr, "%s: popen('%s', 'r') failed\n", argv[0], cmd); 
  33.         exit(EXIT_FAILURE); 
  34.     } 
  35.     /* Read one byte using getc: */ 
  36.     n = getc(infile); 
  37.     if (n == EOF) { 
  38.         pclose(infile); 
  39.         exit(EXIT_SUCCESS); 
  40.     } 
  41.     putchar(n); 
  42.  
  43.     /* Read the rest using fread: */ 
  44.     for (;;) { 
  45.         n = fread(buf, 1, BUFSIZ, infile); 
  46.         if (n <= 0) break
  47.         fwrite(buf, 1, n, stdout); 
  48.     } 
  49.     if (pclose(infile) != 0) { 
  50.         fprintf(stderr, "%s: pclose failed\n", argv[0]); 
  51.         exit(EXIT_FAILURE); 
  52.     } 
  53.     exit(EXIT_SUCCESS); 
  54.     return 0; /* just to make compiler happy */