C++ 调用Linux系统命令

180it 2020-10-10 AM 1422℃ 0条

一个简单的C++程序,Test函数用来测试调用Linux的系统命令ls -l

#include<cstdlib>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
 
const int N = 300;
 
void Test(void){
    char line[N];
    FILE *fp;
    string cmd = "ls -l";
    // system call
    const char *sysCommand = cmd.data();
    if ((fp = popen(sysCommand, "r")) == NULL) {
        cout << "error" << endl;
        return;
    }
    while (fgets(line, sizeof(line)-1, fp) != NULL){
        cout << line << endl;
    }
    pclose(fp);
}
 
int main(){
    Test();
    return 0;
}
 
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

C++ 调用Linux系统命令