在C++20中,可以使用std::filesystem::current_path()函数获取当前工作目录,然后使用std::system()函数执行Windows命令并获取输出。

示例代码:

#include <iostream>
#include <string>
#include <filesystem>

int main() {
    // 获取当前工作目录
    auto current_path = std::filesystem::current_path();
    std::cout << "Current path: " << current_path << std::endl;

    // 执行命令并获取输出
    std::string command = "dir";
    std::string output;
    std::array<char, 128> buffer;
    std::shared_ptr<FILE> pipe(_popen(command.c_str(), "r"), _pclose);
    if (!pipe) {
        std::cerr << "Failed to execute command." << std::endl;
        return 1;
    }
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        output += buffer.data();
    }
    std::cout << "Command output: " << std::endl << output << std::endl;

    return 0;
}

此代码将执行dir命令并获取输出。_popen()函数用于打开一个进程,并返回一个指向进程输出的文件指针。_pclose()函数用于关闭进程。

在上面的示例中,我们使用了std::arraystd::shared_ptr来避免了内存泄漏。我们使用fgets()函数来获取进程输出,直到获取到nullptr为止。最后,我们将输出保存到字符串中,并将其打印到控制台上。

请注意,此代码仅适用于Windows操作系统。如果您需要在其他操作系统上执行命令,请使用相应的命令和函数。

c++20 执行windows命令并获取输出

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

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