linux下c调用shell命令,以及判断文件是否存在

来源:互联网 发布:画苯环的软件 编辑:程序博客网 时间:2024/06/18 16:37

1. linux下c调用shell命令的方法

方法:使用  popen()  函数 ,需要包含头文件  #include  <stdio.h>

代码如下:

#include <stdio.h>#include <stdlib.h>#include <iostream>using namespace std;int main(void){    FILE *fp;    fp = popen("ls /home", "w");    if (NULL == fp) {        cout << "error" << endl;    }    pclose(fp);    return 0;}


2. 检查文件是否存在

方法: 使用access() 函数,需要包含头文件 #include <unistd.h>

代码如下:

#include <stdio.h>#include <stdlib.h>#include <iostream>#include <unistd.h>using namespace std;int main(void){    if (access("/home/1.txt", F_OK) == -1) {        cout << "不存在" << endl;    }    return 0;}

access() 函数:  

存在,返回0 ;   

不存在,返回-1



---

0 0
原创粉丝点击