c++ - 如何在 C++ 中使用 system() 抛出异常?

标签 c++ linux exception

我正在尝试使用

system("mkdir -p a/b/c/d")

用C++在linux中创建一个目录。我目前对C++的异常处理流程还不太了解。使用 try/catch 抛出异常的正确方法是什么?如果命令执行失败,我应该抛出什么异常?

最佳答案

Boost.Filesystem 更容易使用,更安全,而且定义明确。 (或 C++17 中的 <experimental/filesystem> )。请使用此解决方案。

#include <boost/filesystem.hpp>

int main()
{
    namespace fs = boost::filesystem;
    fs::create_directories("/tmp/path/to/dir");
    fs::create_directories("/dev/null");
}
<小时/>

返回值system是实现定义的,但通常期望是被调用命令返回的状态代码。因此,如果您的命令返回 0 以外的内容它失败了。

#include <cstdlib>
#include <stdexcept>

int main()
{
    if ( std::system("mkdir -p /tmp/path/to/dir") != 0 )
        throw std::runtime_error("Could not create directory");

    if ( std::system("mkdir -p /dev/null") != 0 )
        throw std::runtime_error("Could not create directory");
}

关于c++ - 如何在 C++ 中使用 system() 抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46146097/

相关文章:

java - 环回连接失败

c++ - 使用函数输出字符串或字符。小白

regex - 在bash中替换密码参数值

linux - 将大量文件夹中的 txt 和 csv 文件合并为一个大 csv 文件

linux - 将输出通过管道传输到 shell 脚本 |亚马逊Linux

python - 在 python 方法中处理异常的正确方法是什么?

c++ - 存在导出时导入库不构建

c++ - 函数特化 : Which is the declaration?

c# - C# 中的 C++ 库 - 继承类

java - 我应该如何将 SQLException 包装到未经检查的?