C++ : Convert fileparts Matlab Code

If you use Matlab, we can get pathname, filename and extension from input full string path. How if we want extract dirname, filename and extension in C++ ? I want to get pathdir, filename and extension from input string. I have created a simple code how to extract path, filename and extension from fullpath string in C++. Please check below code :

#include <iostream>
#include <string>
using namespace std;

void fileparts(string str, string separator, string *path, string *filename, string *extension)
{
	string spath, sfile, sext;
	string tmp;
	
	spath = str.substr(0, str.find_last_of(separator));
	tmp = str.substr(spath.size()+separator.size(), str.length());
	sfile = tmp.substr(0, tmp.find_last_of("."));
	sext = tmp.substr(sfile.size(), tmp.size());
	
	*path = spath;
	*filename = sfile;
	*extension = sext;
}

int main(int argc, char **argv)
{
	string path;
	string filename;
	string extension;
	fileparts("C:\\dir1\\dir2\\filename.txt", "\\", &path, &filename, &extension);
	cout<<"path="<<path<<endl;
	cout<<"file="<<filename<<endl;
	cout<<"ext="<<extension<<endl;
	return(1);
}

Save code to fileparts.cpp. Compile code using command :

g++ fileparts.cpp -o fileparts

Below is result from running code above :

C:\temp\listdir>fileparst.exe
path=C:\dir1\dir2
file=filename
ext=.txt

Using above code, we can extract dirname, filename and extension from input of string using C++.

Add a Comment

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