c++写shell命令
时间: 2023-11-18 09:56:03 浏览: 36
C++可以通过调用系统的shell来执行命令。下面是一个示例代码,可以在C++函数里面调用shell,并且执行命令,取回命令执行结果:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
string exec(const char* cmd) {
char buffer[128];
string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw runtime_error("popen() failed!");
try {
while (fgets(buffer, sizeof(buffer), pipe) != NULL) {
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
int main() {
string result = exec("ls -l");
cout << result << endl;
return 0;
}
这个示例代码中,exec函数接收一个命令字符串作为参数,然后调用popen函数来执行这个命令,并且读取命令执行结果。最后,函数返回命令执行结果的字符串。
需要注意的是,这个示例代码只是一个简单的例子,实际上在执行命令时还需要考虑很多细节问题,比如命令参数的转义、命令执行的安全性等等。如果需要在实际项目中使用这个功能,建议使用成熟的第三方库来实现。