Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ how to remove filename from path string

I have

const char *pathname = "..\somepath\somemorepath\somefile.ext";

how to transform that into

"..\somepath\somemorepath"

?

like image 486
Mat Avatar asked Apr 28 '12 15:04

Mat


People also ask

How do I delete a filename from path?

GetDirectoryName (Remove File From Path)Use the Path. GetDirectoryName method from the System.IO namespace. Remove the file name from the path.

How do I get the full path of a filename?

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).


4 Answers

The easiest way is to use find_last_of member function of std::string

string s1("../somepath/somemorepath/somefile.ext"); string s2("..\\somepath\\somemorepath\\somefile.ext"); cout << s1.substr(0, s1.find_last_of("\\/")) << endl; cout << s2.substr(0, s2.find_last_of("\\/")) << endl; 

This solution works with both forward and back slashes.

like image 199
Sergey Kalinichenko Avatar answered Sep 17 '22 13:09

Sergey Kalinichenko


On Windows use _splitpath() and on Linux use dirname()

like image 42
acraig5075 Avatar answered Sep 17 '22 13:09

acraig5075


On Windows 8, use PathCchRemoveFileSpec which can be found in Pathcch.h

PathCchRemoveFileSpec will remove the last element in a path, so if you pass it a directory path, the last folder will be stripped.
If you would like to avoid this, and you are unsure if a file path is a directory, use PathIsDirectory

PathCchRemoveFileSpec does not behave as expected on paths containing forwards slashes.

like image 32
roob Avatar answered Sep 21 '22 13:09

roob


use strrchr() to find the last backslash and strip the string.

char *pos = strrchr(pathname, '\\');
if (pos != NULL) {
   *pos = '\0'; //this will put the null terminator here. you can also copy to another string if you want
}
like image 27
Not_a_Golfer Avatar answered Sep 21 '22 13:09

Not_a_Golfer