Getting a directory name from a filename
Asked Answered
M

11

103

I have a filename (C:\folder\foo.txt) and I need to retrieve the folder name (C:\folder) in C++. In C# I would do something like this:

string folder = new FileInfo("C:\folder\foo.txt").DirectoryName;

Is there a function that can be used in C++ to extract the path from the filename?

Mahican answered 18/6, 2010 at 17:2 Comment(0)
O
24

There is a standard Windows function for this, PathRemoveFileSpec. If you only support Windows 8 and later, it is highly recommended to use PathCchRemoveFileSpec instead. Among other improvements, it is no longer limited to MAX_PATH (260) characters.

Outdate answered 18/6, 2010 at 17:12 Comment(2)
Note that this function is now deprecated. The suggestion from Microsoft is to use PathCchRemoveFileSpec instead.Totalitarian
@Default: PathCchRemoveFileSpec is only available starting with Windows 8. Since Windows Vista and 7 are still supported, so is PathRemoveFileSpec.Abdulabdulla
E
168

Using Boost.Filesystem:

boost::filesystem::path p("C:\\folder\\foo.txt");
boost::filesystem::path dir = p.parent_path();
Embattle answered 18/6, 2010 at 17:11 Comment(3)
p.remove_filename() will modify p in-place, and may be implemented more efficiently than p = p.parent_path()Abattoir
If you might also deal with directories be aware of the fact that parent_path() from "C:\\folder" will result in "C:".Waistline
lots of boost gets upgraded to std so also try this .... include <filesystem> .... std::experimental::filesystem::path p("C:\\folder\\foo.txt");Thirtythree
S
84

Example from http://www.cplusplus.com/reference/string/string/find_last_of/

// string::find_last_of
#include <iostream>
#include <string>
using namespace std;

void SplitFilename (const string& str)
{
  size_t found;
  cout << "Splitting: " << str << endl;
  found=str.find_last_of("/\\");
  cout << " folder: " << str.substr(0,found) << endl;
  cout << " file: " << str.substr(found+1) << endl;
}

int main ()
{
  string str1 ("/usr/bin/man");
  string str2 ("c:\\windows\\winhelp.exe");

  SplitFilename (str1);
  SplitFilename (str2);

  return 0;
}
Stumper answered 18/6, 2010 at 17:7 Comment(1)
This is the best minimal solution here.Asylum
H
63

In C++17 there exists a class std::filesystem::path using the method parent_path.

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
    for(fs::path p : {"/var/tmp/example.txt", "/", "/var/tmp/."})
        std::cout << "The parent path of " << p
                  << " is " << p.parent_path() << '\n';
}

Possible output:

The parent path of "/var/tmp/example.txt" is "/var/tmp"
The parent path of "/" is ""
The parent path of "/var/tmp/." is "/var/tmp"
Heterophyte answered 10/5, 2017 at 8:4 Comment(3)
There also exists a .remove_filename() method.Selfsufficient
Thanks, @Qqwy, it also allows to use directory path with that method to get correct and expected results unlike the approach from the answerOrts
Just be aware that std::filesystem::path may use std::wstring instead of std::string on some platforms, making it difficult to interoperate with normal strings...Pappy
O
24

There is a standard Windows function for this, PathRemoveFileSpec. If you only support Windows 8 and later, it is highly recommended to use PathCchRemoveFileSpec instead. Among other improvements, it is no longer limited to MAX_PATH (260) characters.

Outdate answered 18/6, 2010 at 17:12 Comment(2)
Note that this function is now deprecated. The suggestion from Microsoft is to use PathCchRemoveFileSpec instead.Totalitarian
@Default: PathCchRemoveFileSpec is only available starting with Windows 8. Since Windows Vista and 7 are still supported, so is PathRemoveFileSpec.Abdulabdulla
T
17

Why does it have to be so complicated?

#include <windows.h>

int main(int argc, char** argv)         // argv[0] = C:\dev\test.exe
{
    char *p = strrchr(argv[0], '\\');
    if(p) p[0] = 0;

    printf(argv[0]);                    // argv[0] = C:\dev
}
Terra answered 7/1, 2016 at 22:58 Comment(2)
This is not portable. Path separator in linux is '/'. std::filesystem::path is standard and portable.Oralee
Its not robust, but can be made portable. Portability is not always required. I prefer this than ask someone to upgrade to C++17 or install Boost.Cleptomania
B
9
 auto p = boost::filesystem::path("test/folder/file.txt");
 std::cout << p.parent_path() << '\n';             // test/folder
 std::cout << p.parent_path().filename() << '\n';  // folder
 std::cout << p.filename() << '\n';                // file.txt

You may need p.parent_path().filename() to get name of parent folder.

Blent answered 27/7, 2018 at 16:41 Comment(0)
H
4

Use boost::filesystem. It will be incorporated into the next standard anyway so you may as well get used to it.

Hyperplasia answered 18/6, 2010 at 17:11 Comment(4)
Which standard are you talking about? I know that a lot of things from boost were added to C++ std lib, filesystem will be added too?Sciurine
"It will be incorporated into the next standard anyway" And it's notBealle
@AntonK maybe C++ 2017?Heterophyte
@AlessandroJacopson Cool, it seems included in C++17 - en.cppreference.com/w/cpp/filesystemBealle
C
3

I'm so surprised no one has mentioned the standard way in Posix

Please use basename / dirname constructs.

man basename

Chapiter answered 21/7, 2017 at 22:40 Comment(1)
The POSIX functions are not without their drawbacks. In particular they may modify the buffer that you pass in, (they really do mean the signature is basname(char * path) and not basename(const char * path)), and implementations that don't do that appear to have to use a static buffer which makes them thread-unsafe (in principle you could also return dynamically allocated results, but that makes you dependent on alloc family functions which is awkward in C++).Eastereasterday
B
1

_splitpath is a nice CRT solution.

Breban answered 18/6, 2010 at 17:39 Comment(0)
R
-1

Standard C++ won't do much for you in this regard, since path names are platform-specific. You can manually parse the string (as in glowcoder's answer), use operating system facilities (e.g. http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx ), or probably the best approach, you can use a third-party filesystem library like boost::filesystem.

Recap answered 18/6, 2010 at 17:9 Comment(1)
The standard's C++1z is currently attempting to adopt the boost filesystem library as of now making platform-friendliness much less of an issue. It's still in the experimental headers for MSVC, at least.Alaster
M
-6

Just use this: ExtractFilePath(your_path_file_name)

Mikkimiko answered 10/3, 2015 at 2:18 Comment(1)
I believe this is a Delphi method, not something in C++.Calcariferous

© 2022 - 2024 — McMap. All rights reserved.