In this article we will discuss different ways to get filename from a path with or without extension using,

  • Boost Filesystem Library
  • C++17 Filesystem Library
  • Prior to c++11 Days

Suppose we have a file path i.e.

We want to fetch file name from this path i.e. “data.csv” and “data” (With or without extension).

Let’s see how to do that,

Get FileName using Boost & C++17 FileSystem Library

Both Boost & C++17 FileSystem Library provides similar API under different name spaces.

Let’s see how to do that,

Create Path object from given string i.e.

Then check if given path has a stem and if yes then get that stem.

stem here represents the filename with extension.

To get the file name without extension all the filename() function on path i.e.

Checkout complete function as follows,

To use the above function with Boost File System Library, use following header file and namesapce,

To use the above function with C++17 FileSystem Library, use following header file and namesapce,

Complete executable example using Boost is as follows,

Output:

To compile the above code in linux using Boost Filesystem Library, use following command,

To compile the above code in C++17, change the header file and namespace as mentioned above and use following command,

Get File Name using C++ std::string functions

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.