In this article we will dicuss different ways to extract extension from a given path string using different technique i.e.

  • C++17 FileSystem Library
  • Boost FileSystem Library
  • C++ STL

Suppose given file is,

It’s extension should be .out.

Fetch extension of a given file using Boost Filesystem Library & C++17

Both boost filesystem library & C++17 Filesystem provides 2 member function for path class under different namespaces i.e. std::experimental::filesystem for C++17 & boost::filesystem for Boost Filesystem Library.

path path::extension() const;

It returns the path object pointing to the extension component of given path object. If file has no extension then it will return empty path object.

bool path::has_extension() const;

Returns true if given file in path object has extension.

Use these to get the extension of a given file.

It will return empty string if given file has no extension.

In case of c++17 use this header file and namespace,

In case of Boost Library use this header file and namespace,

Complete boost example,

Output:

To compile the above example using Boost, use following command,

To compile the above example using C++17, use following command,

Fetch extension of a given file using std::string functions

Steps to search for an extension in given path string,

  • Search for the last occurrence of ‘.’
  • If exists then return the substring from occurrence of ‘.’ to last chaarcter.
  • Else return empty string.

Complete example is as follows,

Output:

 

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,