C++系统相关操作1 - 调用命令行并获取返回值

1. 关键词

关键词:

C++ 系统调用 system popen 跨平台

应用场景:

希望直接调用操作系统的某些命令,并获取命令的返回值。

2. sysutil.h

#pragma once

#include <cstdint>
#include <string>

namespace cutl
{
    /**
     * @brief Execute a system command.
     *
     * @param cmd the command to be executed.
     * @return true if the command is executed successfully, false otherwise.
     */
    bool system(const std::string &cmd);
    /**
     * @brief Execute a system command and get the output.
     *
     * @param cmd the command to be executed.
     * @param result the output of the command.
     * @return true if the command is executed successfully, false otherwise.
     */
    bool callcmd(const std::string &cmd, std::string &result);
} // namespace cutl

不需要返回值时,可以直接使用system, 需要获取返回值时,可以调用callcmd。

3. sysutil.cpp


#include <map>
#include <iostream>
#include <strutil.h>
#include <cstdlib>
#include "sysutil.h"
#include "inner/logger.h"
#include "inner/system_util.h"
#include "inner/filesystem.h"

namespace cutl
{
    bool system(const std::string &cmd)
    {
        return call_system(cmd);
    }

    bool callcmd(const std::string &cmd, std::string &result)
    {
        // 读取命令执行结果的最大Buffer长度
        constexpr int MAX_CMD_BUF_LEN = 1024;
        FILE *fp = pipline_open(cmd);
        if (fp == NULL)
        {
            CUTL_ERROR("pipline_open error for cmd:" + cmd);
            return false;
        }

        //  读取命令执行结果
        char buffer[MAX_CMD_BUF_LEN] = {0};
        char *res = fgets(buffer, sizeof(buffer), fp);
        if (res == NULL)
        {
            CUTL_ERROR("read result error for cmd:" + cmd);
            if (pipline_close(fp) != 0)
            {
                CUTL_ERROR("pipline_close error for cmd:" + cmd);
            }
            return false;
        }

        if (pipline_close(fp) != 0)
        {
            CUTL_ERROR("pipline_close error for cmd:" + cmd);
        }

        result = strip(std::string(buffer));

        return true;
    }
} // namespace cutl

3.1. system_util_unix.cpp

#if defined(_WIN32) || defined(__WIN32__)
// do nothing
#else

#include "system_util.h"
#include "inner/logger.h"

namespace cutl
{

    bool call_system(const std::string &cmd)
    {
        if (cmd.empty())
        {
            CUTL_ERROR("cmd is empty!");
            return false;
        }

        pid_t status;
        status = std::system(cmd.c_str());

        if (-1 == status)
        {
            CUTL_ERROR("system error!");
            return false;
        }

        if (!WIFEXITED(status))
        {
            CUTL_ERROR("exit status:" + std::to_string(WEXITSTATUS(status)));
            return false;
        }

        if (0 != WEXITSTATUS(status))
        {
            CUTL_ERROR("run shell script fail, script exit code:" + std::to_string(WEXITSTATUS(status)));
            return false;
        }

        return true;
    }

    FILE *pipline_open(const std::string &cmd)
    {
        return popen(cmd.c_str(), "r");
    }

    int pipline_close(FILE *stream)
    {
        return pclose(stream);
    }

} // namespace cutl

#endif // defined(_WIN32) || defined(__WIN32__)

3.2. system_util_win.cpp

#if defined(_WIN32) || defined(__WIN32__)

#include <cstdlib>
#include "system_util.h"
#include "inner/logger.h"

namespace cutl
{

    // https://learn.microsoft.com/zh-cn/cpp/c-runtime-library/reference/system-wsystem?view=msvc-170
    bool call_system(const std::string &cmd)
    {
        if (cmd.empty())
        {
            CUTL_ERROR("cmd is empty!");
            return false;
        }

        int ret = system(cmd.c_str());
        if (ret != 0)
        {
            CUTL_ERROR(std::string("system failure, error") + strerror(errno));
            return false;
        }

        return true;
    }

    // https://learn.microsoft.com/zh-cn/cpp/c-runtime-library/reference/popen-wpopen?view=msvc-170
    FILE *pipline_open(const std::string &cmd)
    {
        return _popen(cmd.c_str(), "r");
    }

    // https://learn.microsoft.com/zh-cn/cpp/c-runtime-library/reference/pclose?view=msvc-170
    int pipline_close(FILE *stream)
    {
        return _pclose(stream);
    }

} // namespace cutl

#endif // defined(_WIN32) || defined(__WIN32__)

4. 测试代码

#include "common.hpp"
#include "sysutil.h"

void TestSystemCall()
{
    PrintSubTitle("TestSystemCall");

    bool ret = cutl::system("echo hello");
    std::cout << "system call 'echo hello', return: " << ret << std::endl;

    auto cmd = "cmake --version";
    std::string result_text;
    ret = cutl::callcmd(cmd, result_text);
    std::cout << "callcmd " << cmd << ", return: " << ret << std::endl;
    std::cout << "callcmd " << cmd << ", result text: " << result_text << std::endl;
}

5. 运行结果

-------------------------------------------TestSystemCall-------------------------------------------
hello
system call 'echo hello', return: 1
callcmd cmake --version, return: 1
callcmd cmake --version, result text: cmake version 3.28.3

6. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

本文由博客一文多发平台 OpenWrite 发布!

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
如果你使用 OpenCV 的 C 接口,你可能需要使用 C 的 glob 函数来获取指定目录下的文件列表。但是,如果你在调用 glob 函数时没有匹配到任何文件,它会返回一个错误代码,这可能会导致程序崩溃。 为了避免这种情况,你可以在调用 glob 函数之前检查目录是否存在,并且使用 glob 的返回值来检查是否有文件匹配成功。 以下是一个示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <glob.h> #include <opencv2/opencv.hpp> int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s <directory>\n", argv[0]); return -1; } // 检查目录是否存在 if (access(argv[1], F_OK) != 0) { printf("Directory does not exist: %s\n", argv[1]); return -1; } // 使用 glob 获取文件列表 glob_t glob_result; int ret = glob(argv[1], GLOB_TILDE, NULL, &glob_result); if (ret != 0) { printf("Failed to get file list: %s\n", strerror(errno)); return -1; } // 检查是否有文件匹配成功 if (glob_result.gl_pathc == 0) { printf("No file matched.\n"); globfree(&glob_result); return -1; } // 处理文件列表 for (int i = 0; i < glob_result.gl_pathc; i++) { cv::Mat img = cv::imread(glob_result.gl_pathv[i]); if (img.empty()) { printf("Failed to load image: %s\n", glob_result.gl_pathv[i]); } else { // 处理图片 } } globfree(&glob_result); return 0; } ``` 在这个示例代码中,我们首先检查了命令行参数是否正确,然后检查了指定的目录是否存在。接着,我们使用 glob 函数获取文件列表,并检查是否有文件匹配成功。最后,我们遍历文件列表,读取图片并进行处理。在结束程序之前,我们使用 globfree 函数释放内存。 希望这个示例代码可以帮助你解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌尘(MoChen)

爱打赏的人技术成长更开哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值