How to get the extension of a file in C++

In this tutorial, we will learn how to get the extension of a file in C++. We will create a function and pass the name of the file as an argument and give the output as the extension of the file. Let’s discuss it in detail.

We need to follow a few steps to get the extension of a file in C++. These are discussed here.

  • We create a function extension() and pass the filename which is a string as an argument in the function.
  • This function stores the position of the last “.” in the passed string.
  • Then it stores the substring after “.” in a different string variable.
  • That’s it. Now, we can print the substring which is the extension of the given file.

Also read: Rename a File in C++?

C++ program to get the extension of a file by the file name

Below you can see the C++ code implementation of the above algorithm:

#include <iostream>
#include <string.h>

using namespace std;

void extension(string file_name);

int main()
  cout<<"Example program to find file extension.\n\n\n";
  return 0;

void extension(string file_name)
  //store the position of last '.' in the file name
  int position=file_name.find_last_of(".");
  //store the characters after the '.' from the file_name string
  string result = file_name.substr(position+1);
  //print the result
  cout<<"The file "<< file_name<<" has <." << result << "> extension."<<endl;

And the output of the above program will be:

Example program to find file extension.

The file this_file.txt has <.txt> extension.
The file thisfile.txt has <.txt> extension.
The file this\file.txt has <.txt> extension.
The file \this\file.txt has <.txt> extension.
The file \this.file.txt has <.txt> extension.

In our C++ program, you can see, we have used find_last_of() function of std::string class to find the rightmost ‘.’ in the file name. And then we have stored the following substring using the substr() function. This is the resultant string which returns us the extension of the file.

The resultant string is printed as the output before the return statement. Note that while calling the function we have used “//” instead of ‘/’ to specify the directories because ‘/’ is a special character.

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *