How to Extract File Name and Extension From a Path in C++?
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.
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
Please Login to comment...