温馨提示×

C++与Linux命令行如何交互

小樊
52
2025-09-25 19:23:13
栏目: 编程语言

在C++程序中与Linux命令行交互通常涉及两种主要方法:使用系统调用和使用管道

  1. 使用系统调用(system()函数)

C++程序可以使用system()函数来执行Linux命令行命令。system()函数接受一个字符串参数,该字符串表示要执行的命令。例如:

#include <cstdlib>

int main() {
    system("ls -l");
    return 0;
}

这个程序将执行ls -l命令并显示其输出。需要注意的是,system()函数会阻塞程序的执行,直到命令执行完成。

  1. 使用管道(popen()函数)

popen()函数允许C++程序创建一个管道,以便将数据发送到另一个进程或从另一个进程接收数据。这使得你可以在C++程序中执行Linux命令并处理其输出。例如:

#include <iostream>
#include <cstdio>
#include <memory>
#include <stdexcept>

std::string exec(const char* cmd) {
    std::array<char, 128> buffer;
    std::string result;
    std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        result += buffer.data();
    }
    return result;
}

int main() {
    std::string output = exec("ls -l");
    std::cout << output;
    return 0;
}

这个程序使用popen()函数执行ls -l命令,并将输出存储在output字符串中。然后,它将输出打印到控制台。

这两种方法都可以实现C++与Linux命令行的交互,但使用管道的方法更加灵活,因为它允许你处理命令的输出和错误流,以及向命令发送输入。而system()函数则仅限于执行命令并获取其退出状态。

0