在Linux中使用popen的例子.
来源:互联网 发布:知乎 阿子 编辑:程序博客网 时间:2024/05/05 02:50
在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打开的文件中获取的是什么数据?
获取的就是脚本输出到标准输出的数据。
- 在Linux中使用popen的例子.
- popen使用的小例子
- 使用popen的一个例子
- linux的popen函数使用
- popen 使用例子 c与sh,管道的结合使用
- Linux popen函数的使用总结
- Linux popen函数的使用总结
- Linux popen函数的使用总结
- Linux popen函数的使用总结
- Linux popen函数的使用总结
- linux下popen的使用心得
- Linux popen()函数使用
- 在C程序中使用popen调用shell脚本程序
- Linux c的popen()
- Linux 的popen函数
- popen()的使用心得
- popen的使用
- popen的使用
- 关于证书文件ie中不能下载的问题
- 闰年的计算方法及程序算法的实现
- 模式的应用
- 甲骨文开发者大会动手实践
- 什么是反射?
- 在Linux中使用popen的例子.
- near指针和far指针
- 说说爬虫(spider) 的实现
- 整理了一个新的TRIGGER供学习之用
- IPMSG飞鸽传书的文件结构
- 使用ASMX的XML Web服务与使用SOAP的.NET Remoting的区别
- 一些有道理的话
- 将CMD命令输出到控制台
- 类型系统是由XMLSchema表示的吗?CLS是XMLSchema表示的吗?