How to Extract File Name and Extension From a Path in C++?
Last Updated :
27 Nov, 2022
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++
#include <filesystem>
#include <iostream>
using namespace std;
int main()
{
char * filepath = "C:\\Users\\Drunk\\Desktop\\l.png" ;
filesystem::path p(filepath);
cout << "filename and extension: " << p.filename()
<< std::endl;
cout << "filename only: " << p.stem() << std::endl;
cout << "Extension: " << p.extension();
return 0;
}
|
Output:
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
Share your thoughts in the comments
Please Login to comment...