MST
星途 面试题库

面试题:C++中如何执行简单系统命令并获取其输出

在C++中,要求你编写一段代码执行系统命令`ls -l`,并将命令执行的输出结果存储到一个字符串变量中,简要说明你使用的方法及其原理。
40.1万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>

std::string executeCommand(const char* command) {
    std::string result;
    FILE* pipe = popen(command, "r");
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }
    char buffer[128];
    while (!feof(pipe)) {
        if (fgets(buffer, 128, pipe) != nullptr) {
            result += buffer;
        }
    }
    pclose(pipe);
    return result;
}

int main() {
    std::string output = executeCommand("ls -l");
    std::cout << "Command output:\n" << output << std::endl;
    return 0;
}

方法及原理

  1. 方法:使用popen函数来执行系统命令,并将命令的输出通过管道读入程序。popen函数会创建一个管道,连接到一个新的进程,该进程执行指定的命令。
  2. 原理
    • popen函数第一个参数是要执行的系统命令,第二个参数指定打开管道的模式,这里使用"r"表示以读模式打开,意味着可以从命令的标准输出读取数据。
    • 使用fgets函数从管道中逐行读取数据,并将读取到的内容追加到字符串变量result中。
    • 最后使用pclose函数关闭管道,释放相关资源。