博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux 下c语言调用终端命令
阅读量:4596 次
发布时间:2019-06-09

本文共 1546 字,大约阅读时间需要 5 分钟。

#include 
#include
#include
#define MAX_SIZE 1024int main(){ FILE *fstream = NULL; int error=0; char buff[MAX_SIZE]={0}; if(NULL == (fstream=popen("ls -r","w")))//这个应该是写方式的管道 { fprintf(stderr,"execute command failed:%s",strerror(error)); return -1; } if(NULL != fgets(buff,sizeof(buff),fstream)) { printf("%s",buff); } else { pclose(fstream); return -1; } pclose(fstream); printf("Hello world!\n"); return 0;}

上面的函数功能,就是ls -r这个命令的结果输出到调试窗口

下面是输入的版本:主要是调用popen函数,这个函数的缺点是要默认的开启一个sh

#include 
#include
#include
#include
#define MAX_SIZE 1024void InputShell(char * shell){ FILE *read_fp = NULL; char buffer[MAX_SIZE]; int chars_read = 0; memset(buffer, 0, sizeof(buffer)); read_fp = popen(shell, "r"); if (read_fp != NULL) { chars_read = fread(buffer, sizeof(char), MAX_SIZE, read_fp); while (chars_read > 0)//读取多数shell命令,shell命令比较长。 { buffer[chars_read - 1] = 0; printf("Reading:\n%s\n", buffer); chars_read = fread(buffer, sizeof(char), MAX_SIZE, read_fp); } pclose(read_fp); //return EXIT_SUCCESS; }}int main(){ char shell[MAX_SIZE] = {0} ;//= NULL; //while(1) //{ scanf("%s",shell); //gets(shell); InputShell(shell); //} return EXIT_FAILURE;}

转载于:https://www.cnblogs.com/wuyida/archive/2013/04/01/6301478.html

你可能感兴趣的文章
C++中获取文件大小的几种途径汇总~
查看>>
JavaScript原始基础
查看>>
JDBC_基础6步骤- 及优化
查看>>
WCM重启报数据库启动错误
查看>>
totoise svn误将桌面作为checkout路径,界面一堆?
查看>>
java写"\n"写入到txt文本用记事本打开出现黑框解决方案
查看>>
第三章例3-7
查看>>
心得五
查看>>
react antD moment
查看>>
MySql创建指定字符集的数据库
查看>>
bzoj 3172 AC自动机
查看>>
rabbitmq
查看>>
解决Latex中Itemize距离过大的问题
查看>>
1打印沙漏
查看>>
LeetCode | Rotate List
查看>>
CodeForces - 455D
查看>>
【转】Django模糊查询
查看>>
Bugtags 创业一年总结
查看>>
UML建模原理
查看>>
[BZOJ 1083] [SCOI2005] 繁忙的都市
查看>>