I want to check a path from a users input. The input must provide a path of a file which does not exist. Further, if the input also provides directories, these directories must exists.
Example inputs:
/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
The code below shows an example. I hope that it archieve my goal but I have still one question.
How can I get rid of output.parent_path().string().size() != 0 as it seems a bit ugly to me?
#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);
}
}