-1

I have a a file path as std::string

For example: C:\\folder1\\folder2\\file.dll

I want to get the folder path

For example: C:\folder1\folder2\.

I tried str=path.substr(0,path.find_last_of("\\/"))

But, this ommits the last \\ also.

Gardener
  • 2,591
  • 1
  • 13
  • 22
Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123
  • 2
    so add 1 to the result of find_last_of – pm100 Oct 29 '18 at 15:35
  • 3
    Instead of handling paths and their handling yourself, I recommend you use either [`std::filesystem::path`](https://en.cppreference.com/w/cpp/filesystem/path) (if your compiler is new enough to have C++17, or otherwise [Boost filesystem `path`](https://www.boost.org/doc/libs/1_68_0/libs/filesystem/doc/reference.html#class-path) otherwise). It will make all your path handling *so* much simpler. – Some programmer dude Oct 29 '18 at 15:37

2 Answers2

1

If you have access to boost, use:

boost::filesystem::path(str).root_path();

and with C++17:

std::filesystem::path(str).root_path();
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
1
  • Use std::filesystem::parent_path():

    std::filesystem::path p{ "c:\\temp\\test.txt" };
    std::cout << "Parent: " << p.parent_path() << std::endl; // will output c:\temp
    
  • If you are using VS 2017, filesystem is available under experimental namespace:

    std::experimental::filesystem::path p{ "c:\\temp\\test.txt" };
    
  • Under Windows you may also combine _splitpath and _makepath to build the parent path.
zdf
  • 4,382
  • 3
  • 18
  • 29