Ubuntu系统c++中执行命令行语句并获取打印结果结果为整型
在Ubuntu系统中,可以使用popen函数来执行命令行语句并获取打印结果。以下是一个示例代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
int executeCommandAndGetResult(const char* command) {
FILE* pipe = popen(command, "r");
if (!pipe) {
std::cerr << "Error executing command." << std::endl;
return -1;
}
char buffer[128];
std::string result;
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != nullptr) {
result += buffer;
}
}
pclose(pipe);
// 将字符串转换为整型
int intResult = std::atoi(result.c_str());
return intResult;
}
int main() {
const char* command = "echo 123";
int result = executeCommandAndGetResult(command);
std::cout << "Result: " << result << std::endl;
return 0;
}
在上述代码中,executeCommandAndGetResult函数用于执行命令行语句并获取打印结果。它使用popen函数来打开一个管道并执行命令,然后通过读取管道输出获取命令的打印结果。最后,将获取到的结果转换为整型并返回。
在main函数中,通过调用executeCommandAndGetResult函数来执行命令echo 123并获取结果。然后将结果打印出来。
请注意,这只是一个简单的示例,如果需要执行复杂的命令或处理更多的情况,可能需要做更多的错误处理和逻辑判断
原文地址: https://www.cveoy.top/t/topic/hInv 著作权归作者所有。请勿转载和采集!