Linux读取shell命令返回的数据

Linux读取shell命令返回的数据

Linux下编写代码时,有时候需要实现的功能已经有shell命令实现了,我们大可不必自己花费精力去实现这部分功能,直接在函数中调用shell命令并且获取到返回的数据,接下来就可以为所欲为了。

代码

/*read linux shell return data*/
/*author: LK*/
#define CMD_1	"ifconfig"
void read_cmd(char * cmd)
{
	FILE *stream;
	//FILE *wstream;
	char buf[1024];
	
	memset(buf, '\0', sizeof(buf));
	stream = popen(cmd, "r");
	//wstream = fopen("test_popen.txt", "w+");
	fread(buf, sizeof(char), sizeof(buf), stream);
	//fwrite(buf, 1, sizeof(buf), wstream);
	pclose(stream);
	//fclose(wstream);
	printf("%s\n", buf);
}

int main(void)
{
	read_cmd(CMD_2);
	return 0;
}

上述代码注释掉的内容为将读取到的数据写入文件。如果读取到的数据太长,可以将数组容量扩大,或者用其他办法。

发布了9 篇原创文章 · 获赞 11 · 访问量 2061

猜你喜欢

转载自blog.csdn.net/u013281532/article/details/103870982
今日推荐