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

1949idc 2年前 (2024-09-18) 阅读数 442 #编程语言

在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上执行相同的操作。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业