C++: How to get filename from a path with or without extension | Boost | C++17 FileSytem Library

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.

"/home/user/sample/temp/data.csv"

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.

Advertisements

Let’s see how to do that,

Create Path object from given string i.e.

// Create a Path object from File Path
filesys::path pathObj(filePath);

Then check if given path has a stem and if yes then get that stem.
// Check if file has stem i.e. filename without extension
if(pathObj.has_stem())
{
	// return the stem (file name without extension) from path object
	return pathObj.stem().string();
}
return "";

stem here represents the filename with extension.

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

pathObj.filename().string();

Checkout complete function as follows,
/*
 * Get File Name from a Path with or without extension
 */
std::string getFileName(std::string filePath, bool withExtension = true)
{
	// Create a Path object from File Path
	filesys::path pathObj(filePath);

	// Check if file name is required without extension
	if(withExtension == false)
	{
		// Check if file has stem i.e. filename without extension
		if(pathObj.has_stem())
		{
			// return the stem (file name without extension) from path object
			return pathObj.stem().string();
		}
		return "";
	}
	else
	{
		// return the file name with extension from path object
		return pathObj.filename().string();
	}

}

To use the above function with Boost File System Library, use following header file and namesapce,
#include <boost/filesystem.hpp>

namespace filesys = boost::filesystem;

To use the above function with C++17 FileSystem Library, use following header file and namesapce,
#include <experimental/filesystem>

namespace filesys = std::experimental::filesystem;

Complete executable example using Boost is as follows,
#include <iostream>
#include <cassert>
#include <string>
#include <boost/filesystem.hpp>

namespace filesys = boost::filesystem;

/*
 * Get File Name from a Path with or without extension
 */
std::string getFileName(std::string filePath, bool withExtension = true)
{
	// Create a Path object from File Path
	filesys::path pathObj(filePath);

	// Check if file name is required without extension
	if(withExtension == false)
	{
		// Check if file has stem i.e. filename without extension
		if(pathObj.has_stem())
		{
			// return the stem (file name without extension) from path object
			return pathObj.stem().string();
		}
		return "";
	}
	else
	{
		// return the file name with extension from path object
		return pathObj.filename().string();
	}

}

int main()
{
	std::string filePath = "/home/user/sample/temp/data.csv";

	// Get File name with extension from file path
	std::string name = getFileName(filePath);


	assert(name == "data.csv");

	std::cout<<name<<std::endl;

	// Get File name with extension from file path
	name = getFileName(filePath, false);

	assert(name == "data");

	std::cout<<name<<std::endl;

	return 0;
}

Output:
data.csv
data

To compile the above code in linux using Boost Filesystem Library, use following command,
g++ -std=c++11 example.cpp -lboost_filesystem -lboost_system

To compile the above code in C++17, change the header file and namespace as mentioned above and use following command,
g++ --std=c++17 example.cpp -lstdc++fs

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

#include <iostream>
#include <cassert>
#include <string>

/*
 * Get File Name from a Path with or without extension
 */
std::string getFileName(std::string filePath, bool withExtension = true, char seperator = '/')
{
	// Get last dot position
	std::size_t dotPos = filePath.rfind('.');
	std::size_t sepPos = filePath.rfind(seperator);

	if(sepPos != std::string::npos)
	{
		return filePath.substr(sepPos + 1, filePath.size() - (withExtension || dotPos != std::string::npos ? 1 : dotPos) );
	}
	return "";
}

int main()
{
	std::string filePath = "/home/user/sample/temp/data.csv";

	// Get File name with extension from file path
	std::string name = getFileName(filePath);

	assert(name == "data.csv");

	std::cout<<name<<std::endl;

	// Get File name with extension from file path
	name = getFileName(filePath, false);

	std::cout<<name<<std::endl;
	assert(name == "data.csv");

	std::cout<<name<<std::endl;

	return 0;
}

Output:
data.csv
data.csv
data.csv

 

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top