C++: How to extract file extension from a path string using Boost & C++17 FileSystem Library

In the previous article, we have discussed about C++11 Lambda : How to capture member variables inside Lambda function. Let us learn how to extract file extension from a path string using Boost in C++ Program.

Extracting file extension from a path string using Boost & C++17 FileSystem Library

In this article we will discuss various ways of extracting an extension from given path string using some technique.

Some prerequisites are-

  1. C++ FileSystem Library
  2. Boost FileSystem Library
  3. C++ STL

i.e if we have given as /home/user/desktop/temp/logs.out then extension should be .out.

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

Let a scenario where we want to get extension in a given path string. For this-

  • Search for ‘.’ where it is lastly occurred.
  • If found return the substring from that ‘.’ to last character.
  • If not found, return a empty string
#include <iostream>
#include <cassert>
#include <string>

std::string getExtension(std::string file_Path)
{
    // Find the last position of '.' in given string path
    std::size_t posn = file_Path.rfind('.');
    // If last '.' in string path is found
    if (posn != std::string::npos) {
        // return the substring
        return file_Path.substr(posn);
    }
    // In case of no extension empty string is returned
    return "";
}
int main()
{
    // File path where '.' is present
    std::string file_Path = "/home/user/desktop/temp/logs.out";
    std::string extension = getExtension(file_Path);
    std::cout<<"Extension with '.' : "<<extension<<std::endl;
    assert(extension == ".out");
    // File path without '.'
    file_Path = "/home/user/desktop/temp/";
    extension = getExtension(file_Path);
    std::cout<<"Extension without '.' : "<<extension<<std::endl;
    assert(extension == "");
    return 0;
}
Output :
Extension with '.' : .out
Extension without '.' :