31

I have

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

how to transform that into

"..\somepath\somemorepath"

?

Mat
  • 4,281
  • 9
  • 44
  • 66

6 Answers6

62

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
11

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

Yennefer
  • 5,704
  • 7
  • 31
  • 44
acraig5075
  • 10,588
  • 3
  • 31
  • 50
7

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.

roob
  • 2,419
  • 3
  • 29
  • 45
3

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
}
Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
2

Supposing you have access to c++17 it should be something like this:

std::filesystem::path fullpath(path_string);
fullpath.remove_filename();
cout << fullpath.string();

If you don't have c++17, but have access to boost, you can do the same thing with boost::filesystem::path.

Using one of these libraries has the advantage of being compatible with multiple operating systems.

John Bowers
  • 1,695
  • 1
  • 16
  • 26
0

PathRemoveFileSpec(...) you dont need windows 8 for this. you will need to include Shlwapi.h and Shlwapi.lib but they are winapi so you dont need any special SDK

Justin
  • 3,255
  • 3
  • 22
  • 20