在Ubuntu系统中,可以使用popen函数来获取命令行的输出结果,并将其转换为整型。以下是一个示例代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>

int getOutputAsInt(const char* cmd) {
    FILE* pipe = popen(cmd, "r");
    if (!pipe) {
        std::cerr << "Error: Failed to open pipe" << std::endl;
        return -1;
    }

    char buffer[128];
    std::string result = "";
    while (!feof(pipe)) {
        if (fgets(buffer, 128, pipe) != NULL) {
            result += buffer;
        }
    }

    pclose(pipe);

    // 将输出结果转换为整型
    int output = std::stoi(result);
    return output;
}

int main() {
    int result = getOutputAsInt("ls -l | wc -l");
    std::cout << "Output: " << result << std::endl;
    return 0;
}

在上述代码中,getOutputAsInt函数接受一个命令作为参数,通过popen函数执行该命令,并读取输出结果。然后,使用std::stoi函数将输出结果转换为整型,并返回该整型值。

main函数中,我们使用了ls -l | wc -l命令来获取当前目录下文件的数量,并将结果输出。

注意:在使用popen函数时,需要小心处理命令的安全性,以防止命令注入等安全问题。

Ubuntu C++ 获取命令行输出并转换为整型

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

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