In this article we will discuss different ways to check if given path is of file or directory that exists using Boost Filesystem Library & C++17 Filesystem Library.

Both Boost Filesystem library & C++17 Experimental filesystem library provides certain functions that we are going to use here, 

bool exists(const path& p);

In Boost Library’s boost::filesystem namespace and In C++17 std::experimental::filesystem namespace,

Both returns true if the given path points to an entity (file or directory) that exists in filesystem. Also, first one throws filesystem_error, where as overload with error_code& throws nothing.

bool is_regular_file(const path& p);

In Boost Library’s boost::filesystem namespace and In C++17 std::experimental::filesystem namespace,

Both returns true if the given path points to a regular file. Also, first one throws filesystem_error, where as overload with error_code & throws nothing.

bool is_directory(const path& p);

In Boost Library’s boost::filesystem namespace and In C++17 std::experimental::filesystem namespace,

Both returns true if the given path points to a directory. Also, first one throws filesystem_error, where as overload with error_code& throws nothing.

Check if given path is a file that exists using Boost FileSystem Library & C++17

Algo is :

  • First convert the given string path to filesystem::path object.
  • Check if given path exists or not using filesystem::exists() API.
  • Check if given path is a regular file using filesystem::is_regular_file() API.

Complete function for is as follows,

For C++17, use the same function , with following header file and namespace i.e.

For Boost Library, use the same function , with following header file and namespace i.e.

Check if given path is a Directory that exists using Boost & C++17 FileSystem Library

Algo is :

  • First convert the given string path to boost::filesystem::path object.
  • Check if given path exists or not using boost::filesystem::exists() API.
  • Check if given path is a directory using boost::filesystem::is_directory() API.

Complete function is as follows,

For C++17, use the same function , with following header file and namespace i.e.

For Boost Library, use the same function , with following header file and namespace i.e.

Complete example with Boost headers is as follows,

 

Compile above example using Boost with following command in linux,

g++ -std=c++11 example.cpp -lboost_filesystem -lboost_system

Compile above example in C++17 after changing header file name and namespace, with following command in linux,

g++ -std=c++17 example.cpp -lstdc++fs

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,