0
我想檢查用戶輸入的路徑。輸入必須提供一個不存在的文件的路徑。此外,如果輸入也提供目錄,則這些目錄必須存在。boost :: filesystem :: path.parent_path()和空格
實施例輸入:
/existent_dir_a/existent_dir_b/existent_file.bin
< - 假
/existent_dir_a/existent_dir_b/non_existent_file.bin
< - 確定
/non_existent_dir_a/non_existent_file.bin
< - 假
non_existent_file.bin
< - 確定
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);
}
}