Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Extract File Name and Extension From a Path in C++?

Improve Article
Save Article
Like Article
  • Last Updated : 27 Nov, 2022
Improve Article
Save Article
Like Article

Prerequisites: Install C++17 or Newer Standard Compiler

It is a common requirement of users to extract filenames and their extensions from a given path. The process is trivial, but it becomes hard under some circumstances (different OS, file types, etc.). This article will teach you how to extract the file name and extension from a path in C++.

Extracting file names and extensions from a Path

Firstly the path to the file is defined in the variable file path. This variable is sent as an argument to the filesystem::path class constructor. Then we use the public member function filename to get the filename and extension from the path. Then used, the stem member function to get the file name, and in the end, used the extension member function to get the file extension.



// C++ Program for Extracting
// file names and extensions from a path
#include <filesystem>
#include <iostream>
using namespace std;
int main()
    // The path to the file
    char* filepath = "C:\\Users\\Drunk\\Desktop\\l.png";
    // Passing the path as argument to the function
    filesystem::path p(filepath);
    // Displaying filename and extensions separately
    // By accessing the respective constructors
    cout << "filename and extension: " << p.filename()
         << std::endl;
    cout << "filename only: " << p.stem() << std::endl;
    cout << "Extension: " << p.extension();
    return 0;


Output of the C++ Program


Note: The above method would also work on extension-less files. They would contain a file name but would have an empty string as the extension. Ex. If the file’s path is changed to




My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!