如何将linux命令的结果复制到使用c代码的string中?

我执行了一个命令“watch grep \”CPU MHz \“/ proc / cpuinfo”。执行这个命令后,我得到了下面的结果。 命令的结果

但是当我尝试使用c代码这个命令。

#include<stdio.h> #include<stdlib.h> int main(){ FILE *fp; char path[1035]; char command[]="watch grep \"cpu MHz \" /proc/cpuinfo"; fp = popen(command, "r"); if (fp == NULL) { printf("Failed to run command\n" ); exit(1); } /* Read the output a line at a time - output it. */ while (fgets(path, sizeof(path)-1, fp) != NULL) { printf("%s",path); } pclose(fp); return 0; } I am getting following result. 

守则的结果告诉我我哪里错了?

尝试这样的事情:

 #include <stdio.h> #include <stdlib.h> int main(void){ FILE *fp; char path[1035]; char command[]="while grep \"cpu MHz\" /proc/cpuinfo; do sleep 2; done"; fp = popen(command, "r"); if (fp == NULL) { printf("Failed to run command\n" ); exit(1); } /* Read the output a line at a time - output it. */ while (fgets(path, sizeof(path), fp) != NULL) { printf("%s",path); } pclose(fp); return 0; } 

我想这是你想要的。 不要忘记使用memset

 #include<stdio.h> #include<stdlib.h> int main() { FILE *fp; char path[1035]; char command[]="watch grep 'cpu MHz' /proc/cpuinfo"; fp = popen(command, "r"); if (fp == NULL) { printf("Failed to run command\n" ); exit(1); } memset(path,'\0',sizeof(path)); /* Read the output a line at a time - output it. */ while (fgets(path, sizeof(path)-1, fp) != NULL) { printf("%s",path); } pclose(fp); return 0; }