【问题标题】:boost::filesystem::create_directory threw a boost::filesystem::filesystem_error: Bad addressboost::filesystem::create_directory 抛出了 boost::filesystem::filesystem_error: Bad address
【发布时间】:2018-05-20 21:41:54
【问题描述】:

我的代码的 TL;DR 如下:

server::server(boost::filesystem::path mappath) : mappath(mappath) {
    if(boost::filesystem::is_directory(mappath) && boost::filesystem::exists(mappath)) {
        // Do some stuff here
    } else {
        boost::filesystem::create_directory(mappath);
    }
}

mappath 存在时,代码可以工作(几乎没有,因为我发现 Boost 在几乎每个函数中都存在段错误)。
但是,如果没有,它会引发异常并显示“错误地址”消息。
当我通过std::cout 打印mappath 时,它返回:

"/home/myusername/.testfolder/huni/ENTER YOUR TEXT HERE"

哪个是正确的。

请注意,当我尝试在 else 语句中打印 mappath inside 时,它会出现段错误。
我推断is_directoryexists 中的mappath 有问题,因为在if 语句之前打印之前 时没有错误。

【问题讨论】:

  • 您可能正在寻找boost::filesystem::create_directories。但这只是猜测,因为我们无法重现您的问题。
  • @DrewDormann 将其替换为 create_directories 后,它现在会在引发异常的位置出现段错误。
  • 我们只能猜测您的程序可能有什么问题。请edit您的问题提供Minimal, Complete, and Verifiable example
  • 有趣的是,当我尝试运行您发布的代码时,我得到了“使用未声明的标识符 'server'”。
  • 不管怎样,制作一个最小的失败程序并在此处发布代码。不幸的是,一个功能无法帮助其他人帮助您。

标签: c++ c++11 boost boost-filesystem


【解决方案1】:

我为自己编写了一个 MCVE。当路径不存在时,boost 抛出

terminate called after throwing an instance of 'boost::filesystem::filesystem_error'
  what():  boost::filesystem::create_directory: No such file or directory
Aborted (core dumped)

因为您的程序首先检查路径是否为目录,然后检查路径是否存在(正确)。

当路径存在且为目录时,程序运行无输出,不执行任何操作(正确)。

当路径存在且是文件时,boost会抛出

terminate called after throwing an instance of 'boost::filesystem::filesystem_error'
  what():  boost::filesystem::create_directory: File exists
Aborted (core dumped)

因为它无法创建目录(正确)。

因此你的 sn-p 做了它应该做的事。也许您应该更改if 语句中的顺序并在else 中添加支票:

#include <boost/filesystem.hpp>
#include <iostream>

class server {
public:
  server(boost::filesystem::path mappath) : mappath(mappath) {
    if(boost::filesystem::exists(mappath) && boost::filesystem::is_directory(mappath)) {
        // Do some stuff here
    } else if (!boost::filesystem::exists(mappath)) {
        boost::filesystem::create_directory(mappath);
    }
  }
private:
  boost::filesystem::path mappath;
};

int main() {
  server s("/path/test");
  return 0;
}

现在程序检查路径是否存在。如果路径存在,则程序检查路径是否为目录。如果路径不存在,则创建目录。

【讨论】:

  • 这不解释Bad address
  • @Dan Joe:正如我展示的代码 sn-p 不会抛出 Bad address。该代码按预期工作。问题一定出在其他地方。
  • 我尝试了你的代码,它为我抛出了Bad address
  • @DanJoe:你如何编译代码?你用的是哪个版本的boost?你在哪个操作系统上工作?
【解决方案2】:

原来Bad address 是一个 POSIX 特定的错误。

另外,我无法在 if 语句的 else 子句中打印 mappath 的原因是 is_directory 弄乱了引用。
我不知道它到底在做什么。

所以,我已经从 Boost 切换到真正有效的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多