How to Get File Extension in C++?
In C++, we may often find the need to extract the file extension from a given path of the file while working in many applications for processing or validating. In this article, we will learn how to get the file extension in C++.
For Example,
Input: someFolder ↳ filename.ext Output: File Extension = .ext
Extracting a File Extension in C++
In C++17 and later, the std::filesystem::path::extension()
function from the std::filesystem
library can be used to retrieve the extension of a file from its path which is like a string wrapper. This function specifically extracts and returns the file extension that can be later used for processing. It is the member function of the std::filesystem::path class so we can call it using the dot operator (.).
C++ Program to Get File Extension
The below program demonstrates how we can get a file extension from a file path in C++.
// C++ Program to demonstrate how we can get a file
// extension from a file path
#include <filesystem>
#include <iostream>
using namespace std;
int main()
{
// Define a path object representing the file path.
filesystem::path filePath
= "C:/Users/Desktop/myFile.txt";
// Print the file extension using the extension() method
// of the path object.
cout << "File extension is: " << filePath.extension()
<< endl;
return 0;
}
Output
File extension is: ".txt"
Explanation: In the above example, we first define the file path and then use the extension()
function to get the file extension. Finally, the extension is printed.
Note: The
extension()
function works only in C++17 and later and it includes the dot in the extension. If the file does not have an extension, it will return an empty string.
Contact Us