Open In App

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

Last Updated : 27 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Code:

C++




// 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:

Output of the C++ Program

Output

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

C:\Users\Apples\touch

Output:

Output


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads