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);

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

g++ fileparts.cpp -o fileparts

Below is result from running code above :


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 *


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