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

时间:2017-09-10 22:22:15

标签: c++ linux exception

我正在尝试使用

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

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

1 个答案:

答案 0 :(得分:0)

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

#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");
}