头文件: #include <stdio.h>
函数说明:
FILE * popen ( const char * command , const char * type ); int pclose ( FILE * stream );
例子一:
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fpin;
FILE *fpout;
char buf[1024];
memset( buf, '\0', sizeof(buf) );//初始化buf,以免后面写如乱码到文件中
fpin = popen( "ls -l", "r" ); //将“ls -l”命令的输出 通过管道读取(“r”参数)到FILE* stream
fpout = fopen( "test_popen.txt", "w+"); //新建一个可写的文件
fread( buf, sizeof(char), sizeof(buf), fpin); //将刚刚FILE* fpin的数据流读取到buf中
fwrite( buf, 1, sizeof(buf), fpout);//将buf中的数据写到FILE* fpout对应的流中,也是写到文件中
pclose( fpin );
fclose( fpout );
return 0;
} [uglychen@chenxun popen]$ gcc popen.c
[uglychen@chenxun popen]$ ./a.out
[uglychen@chenxun popen]$ cat test_popen.txt
total 24
-rwxrwxr-x 1 uglychen uglychen 5680 Jun 14 14:04 a.out
-rw-rw-r-- 1 uglychen uglychen 771 Jun 14 14:03 popen.c
-rw-rw-r-- 1 uglychen uglychen 0 Jun 14 14:05 test_popen.txt
例子二:popen2.c
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//#include <sys/wait.h>
#define PAGER "${PAGER:-more}" /* environment variable, or default */
#define MAXLINE 4096
int main(int argc, char *argv[])
{
char line[MAXLINE];
FILE *fpin, *fpout;
if (argc != 2)
printf("usage: a.out <pathname>");
if ((fpin = fopen(argv[1], "r")) == NULL)
printf("can't open %s", argv[1]);
if ((fpout = popen(PAGER, "w")) == NULL)
printf("popen error");
/* copy argv[1] to pager */
while (fgets(line, MAXLINE, fpin) != NULL) {
if (fputs(line, fpout) == EOF)
printf("fputs error to pipe");
}
if (ferror(fpin))
printf("fgets error");
if (pclose(fpout) == -1)
printf("pclose error");
exit(0);
}
例子三:
原文:http://blog.csdn.net/chenxun_2010/article/details/46497961