温馨提示×

如何在c++中使用管道技术执行cmd命令

c++
小樊
81
2024-09-15 18:39:11
栏目: 编程语言

在C++中,你可以使用popen()函数来创建一个管道并执行CMD命令

#include<iostream>
#include <fstream>
#include<string>

int main() {
    // 要执行的CMD命令
    std::string cmd = "dir";
    
    // 打开管道并执行命令
    FILE* pipe = popen(cmd.c_str(), "r");
    if (!pipe) {
        std::cerr << "Failed to execute command."<< std::endl;
        return 1;
    }

    // 读取命令输出
    char buffer[128];
    std::string result;
    while (fgets(buffer, sizeof(buffer), pipe)) {
        result += buffer;
    }

    // 关闭管道
    pclose(pipe);

    // 输出结果
    std::cout << "Command output: "<< std::endl<< result<< std::endl;

    return 0;
}

这个示例将执行dir命令(列出当前目录下的文件和文件夹),然后将输出读取到result字符串中。请注意,这个示例仅适用于Unix系统(如Linux和macOS)。在Windows上,你需要使用_popen()函数代替popen()

对于Windows系统,请包含<stdio.h>头文件,并将popen()替换为_popen(),将pclose()替换为_pclose()。这是一个适用于Windows的示例:

#include<iostream>
#include <fstream>
#include<string>
#include<stdio.h>

int main() {
    // 要执行的CMD命令
    std::string cmd = "dir";
    
    // 打开管道并执行命令
    FILE* pipe = _popen(cmd.c_str(), "r");
    if (!pipe) {
        std::cerr << "Failed to execute command."<< std::endl;
        return 1;
    }

    // 读取命令输出
    char buffer[128];
    std::string result;
    while (fgets(buffer, sizeof(buffer), pipe)) {
        result += buffer;
    }

    // 关闭管道
    _pclose(pipe);

    // 输出结果
    std::cout << "Command output: "<< std::endl<< result<< std::endl;

    return 0;
}

这个示例将在Windows上执行相同的操作。

0