popen相对于system最大的好处就是可以获取运行的输出结果
popen的头文件和原型:
#include <stdio.h>
FILE* popen(const char* cmdstring, const char* type);
int pclose(FILE *stream);
参数讲解:
cmdstring:终端的指令
type:只有两种形式(只能是读或写的其中一种),一种是“r”,连接到cmdstring的标准输出;一种是“w”,连接到cmdstring的标准输入
直接写一段代码自己来回味一下吧,代码本身没难度:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
int main(){
FILE* fp = popen("date","r");
char* Rbuf = (char*)malloc(1024 * sizeof(char));
int Rtypes = fread(Rbuf,1,1024,fp);
printf("\n%s\n",Rbuf);
pclose(fp);
return 0;
}
运行结果: