c++ - boost::filesystem::path.parent_path() 和空格

标签 c++ boost boost-filesystem

我想检查用户输入的路径。输入必须提供不存在的文件路径。此外,如果输入还提供目录,则这些目录必须存在。

示例输入:

/existent_dir_a/existent_dir_b/existent_file.bin <-- false

/existent_dir_a/existent_dir_b/non_existent_file.bin <-- ok

/non_existent_dir_a/non_existent_file.bin <-- false

non_existent_file.bin <-- ok

existent_file.bin <-- false

下面的代码显示了一个示例。我希望它能实现我的目标,但我还有一个问题。

我怎么能去掉 output.parent_path().string().size() != 0 因为它对我来说有点难看?

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

namespace fs = boost::filesystem;

int main(int ac, char ** av)
{
  fs::path output(av[1]);

  std::cout << output << std::endl;

  std::cout << output.parent_path() << std::endl;

  if (fs::exists(output))
  {
    std::string msg = output.string() + " already exists";

    throw std::invalid_argument(msg);
  }

  if ( output.parent_path().string().size() != 0 &&
       !fs::exists(output.parent_path()) )
  {
    std::string msg = output.parent_path().string() + " is not a directory";

    throw std::invalid_argument(msg);
  }
}

最佳答案

使用 !output.parent_path().empty()

关于c++ - boost::filesystem::path.parent_path() 和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42140235/

相关文章:

c++ - 通过 `void *` 和 C++ `extern "C"` 函数调用在 C 中初始化一个 C++ 类

c++ - 允许用户在 C++ 中的类上定义属性

c++ - boost::iostream bzip2_decompressor 不解压缩由 bzip2_compressor 压缩的文件

c++ - boost filesystem::path 构造函数 std::length_error

c++ - 使用链表制作模板类

c++ - DirectX:在不使用渲染目标的情况下渲染到屏幕缓冲区

c++ - 转换为 LPCTSTR 时出现文件复制问题

c++ - 平台无关的内存映射 [文件] IO

c++ - 如果 Visual Studio 2012 抛出 VS2012 不应存在的编译错误,这意味着什么?

c++ - 我可以使用 boost 文件系统获取文件属性(隐藏/存档...)吗?