我想检查用户输入的路径。输入必须提供不存在的文件路径。此外,如果输入还提供目录,则这些目录必须存在。
示例输入:
/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/