编程语言
首页 > 编程语言> > 系统编程——管道_高级管道

系统编程——管道_高级管道

作者:互联网

高级管道

高级管道:将命令运行结果读入到程序,或将程序运行结果输出到命令
ls -l | grep ^d
“r” “w”
将左边命令的输出作右边命令的输入

步骤

1.调用popen()打开高级管道
FILE *popen(const char *command, const char *type);
@command:shell命令
@type:读写类型,“r”:读 “w”:写
返回文件指针

读fread()或写fwrite();
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

2.调用pclose()关闭高级管道 
int pclose(FILE *stream);

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

int main()
{
#if 0
	//1.将ls -l命令运行的结果存入buf
	FILE *fp = popen("ls -l","r");
	if(NULL == fp)
	{
		perror("popen error");
		return -1;
	}

	char buf[128] = "";
	int count = 0;
	while((count = fread(buf,1,sizeof(buf) - 1,fp)) > 0)
	{
		printf("count = %d,buf = %s\n",count,buf);
		memset(buf,0,sizeof(buf));
	}
#else
//程序运行结果输出到命令
//	FILE *fp = popen("grep world","w");
	FILE *fp = popen("wc -l","w");
	
	if(NULL == fp)
	{
		perror("popen error");
		return -1;
	}

	char buf[128] = "hello\nworld\nabc\n";
	int count = 0;
	count = fwrite(buf,1,strlen(buf),fp);
	printf("fwrite count = %d\n",count);
	pclose(fp);

	pclose(fp);
#endif
}

标签:fp,count,编程,高级,popen,管道,FILE,buf,size
来源: https://blog.csdn.net/abist/article/details/117590719