在Linux下进行编写程序的时候,如果需要执行一段脚本,并且需要获取脚本执行的结果,按么最好使用popen。下面就举一个例子:
c代码文件为: 3.C,内容如下:
- #include <sys/types.h>
- #include <string.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <iostream.h>
- typedef struct tag_Result
- {
- char filename[100];
- int filesize;
- tag_Result()
- {
- filename[0] = '0';
- filesize = 0;
- }
- }RESULT,*LPRESULT;
- int WriteFile(const char *filename,const char *pFile,const int nLen)
- {
- FILE *stream=NULL;
- stream=fopen(filename,"w+");
- if(stream==NULL)
- {
- perror("Open file error");
- return -1;
- }
- if(fwrite((void *)pFile,1,nLen,stream)!=nLen)
- {
- perror("Write file error");
- fclose(stream);
- return -1;
- }
- fclose(stream);
- return 0;
- }
- int main()
- {
- RESULT res;
- FILE *pStream = NULL;
- char buf[4096]={""};
- char dddd[10]={""};
- char cccc[100]={""};
- pStream=popen("a","r");
- if(pStream)
- {
- fscanf(pStream,"%[^';'];%[^';'];%s",res.filename,cccc,dddd);
- cout<<"filename:"<<res.filename<<endl;
- cout<<"cccc:"<<cccc<<endl;
- res.filesize = atoi(dddd);
- cout<<"filesize:"<<res.filesize<<endl;
- sprintf(buf,"%s,%d",res.filename,res.filesize);
- WriteFile("result.txt",buf,strlen(buf));
- pclose( pStream);
- }
- else
- {
- cout<<"popen Error!"<<endl;
- }
- return 1;
- }
要执行的脚本名称为a,脚本内容为:
- #!/bin/sh
- #filename: a
- fileinfo=11
- rm fileinfo #>/dev/null 2>
- echo -n $fileinfo";" >> fileinfo
- echo -n $fileinfo";" >> fileinfo
- ls -l $fileinfo | awk '{print $5 }' >> fileinfo
- cat fileinfo
通过:g++ -o 11 3.C 编译c代码生成可执行文件为:11,直接执行11,就可以查看到结果.
1.问题1: 如果脚本a在第3行的时候,直接就通过exit 1返回了,那么通过popen打开执行这个脚本会出现什么结果呢?
如果脚本直接返回,相当于脚本没有向popen打开的文件中写入任何数据,也就是说popen相当于打开了一个空文件.
2.问题2: popen打开的文件中获取的是什么数据?
获取的就是脚本输出到标准输出的数据。