在Ubuntu系统中,可以使用popen函数来执行命令行语句并获取打印结果。

下面是一个示例代码:

#include <iostream>
#include <cstring>

int main() {
    FILE* pipe = popen("ls", "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) != NULL) {
            result += buffer;
        }
    }

    pclose(pipe);

    std::cout << "Command output:\n" << result << std::endl;

    return 0;
}

在上述示例中,使用popen函数执行了ls命令,并通过循环读取命令输出,将结果存储在result字符串中。最后,关闭管道并打印结果。

可以根据需要修改命令行语句和处理输出的方式

Ubuntu系统c++中执行命令行语句并获取打印结果

原文地址: https://www.cveoy.top/t/topic/hIns 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录