linux下popen函数用法代码
2013-04-20 12:59
537 查看
// linux下popen函数用法代码:zread.c,摘自gzip例子 #include <stdio.h> #include <stdlib.h> #include <string.h> /* Trivial example of reading a gzip'ed file or gzip'ed standard input * using stdio functions fread(), getc(), etc... fseek() is not supported. * Modify according to your needs. You can easily construct the symmetric * zwrite program. * * Usage: zread [file[.gz]] * This programs assumes that gzip is somewhere in your path. */ int main(argc, argv) int argc; char **argv; { FILE *infile; char cmd[256]; char buf[BUFSIZ]; int n; if (argc < 1 || argc > 2) { fprintf(stderr, "usage: %s [file[.gz]]\n", argv[0]); exit(EXIT_FAILURE); } strcpy(cmd, "gzip -dc "); /* use "gzip -c" for zwrite */ if (argc == 2) { strncat(cmd, argv[1], sizeof(cmd)-strlen(cmd)); } infile = popen(cmd, "r"); /* use "w" for zwrite */ if (infile == NULL) { fprintf(stderr, "%s: popen('%s', 'r') failed\n", argv[0], cmd); exit(EXIT_FAILURE); } /* Read one byte using getc: */ n = getc(infile); if (n == EOF) { pclose(infile); exit(EXIT_SUCCESS); } putchar(n); /* Read the rest using fread: */ for (;;) { n = fread(buf, 1, BUFSIZ, infile); if (n <= 0) break; fwrite(buf, 1, n, stdout); } if (pclose(infile) != 0) { fprintf(stderr, "%s: pclose failed\n", argv[0]); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); return 0; /* just to make compiler happy */ }
本文出自 “寒冰潭” 博客,请务必保留此出处http://hanbingtan.blog.51cto.com/2524413/1181942
相关文章推荐
- linux函数代码操练----文件操作篇------02close()函数
- Linux setsockopt和getsockopt函数的用法分析
- linux驱动程序ioctl函数用法
- Linux下Kill函数用法
- Linux中configure/makefile的用法实例(附代码)
- 函数指针使用示例(参考Linux-内核代码)
- linux中函数getopt_long用法解释
- 在 Linux 命令行中使用和执行 PHP 代码(二):12 个 PHP 交互性 shell 的用法
- 3.linux C 用man查各种函数的用法
- Linux Socket编程(不限Linux)基本函数用法
- gcov命令_Linux gcov 命令用法详解:测试程序的代码覆盖率的工具
- whereis命令_Linux whereis 命令用法详解:查找二进制程序、代码等相关文件路径
- linux下的文件操作函数及creat用法
- Linux下Kill函数用法
- eregi_replace与preg_replace 函数代码的用法比较
- linux下getopt函数的用法
- NSLayoutConstraint-代码实现自动布局的函数用法说明
- Linux popen用法
- NSLayoutConstraint-代码实现自动布局的函数用法说明
- Linux 下 popen 函数引起的僵尸进程 defunct 以及解决办法