Get name and extension of file from absolute path in C++

In this tutorial will see the C++ code to get the file name and the extension from its absolute path. The file’s absolute path is a path from its root folder. Each folder is separated by ‘\‘. The filename and its extension are always present at the end (rightmost end) of the path  and separated by ‘.

Step 1: Copy the file’s absolute path in a string named ‘filepath‘.

Step 2: Find the string length of the filepath and declare a temporary string.

Step 3: Now iterate through the string using the loop. If the character is equal to ‘\‘ then clear the content of the temporary string. Else concatenate the characters into the temporary string. After doing this you will get the part of the filepath after the last \ which is our filename with an extension in a temporary string.

Step 4: Now split that string by taking ‘.‘ as a separator. Iterate through the string using for loop print the characters before ‘.‘ as a file name and remaining as an extension.

Here is the full code:

// Get the name and extension of the file from the absolute path in C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
  string filepath = "C:\\Users\\admin\\Desktop\\abc.png";  // The path to the file
  string str;                                              //temporary string
  int n = filepath.length();                               //length of filepath string
  for (int i=0;i<n;i++)                                    //iterate through filepath
  {
    if (filepath[i] != '\\')                             
    {
      str += filepath[i];                                  //concatenate to str
    }
    else
    {
      str.clear();                                         //clear the string str content 
    }
  }
  int len = str.length();                                  //calculate length of last string
  string temp;                                             //another temporary string
  for (int i = 0; i < len; i++)                            //iterate through last
  {
    if (str[i] != '.')
    {
      temp += str[i];                                      //concatenate to temp
    }
    else
    {
      cout<<"Filename : "<<temp<<endl;                     //print filename
      temp.clear();                                        //clear the string temp content
    }
  }
  cout<<"Extension : "<<temp<<endl;                        //print extension
  return 0;
}

Output:

Filename : abc 
Extension : png

Also, refer to Listing all files and sub-directories within a directory in C++

Leave a Reply

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