32

What is the simplest way to get the directory that a file is in? I'm using this to find the working directory.

string filename = "C:\MyDirectory\MyFile.bat" 

In this example, I should get "C:\MyDirectory".

9
  • 3
    Pet hate: is that a narrow STL string? You should be using Unicode strings for all file handling on Windows.
    – Rup
    Dec 15, 2011 at 10:43
  • @Rup: really? Does the encoding matter when looking for '/' and '\'? As long as you are not interpreting the strings as ASCII/Latin1/whatever wrong assumption
    – sehe
    Dec 15, 2011 at 10:50
  • @sehe No, sure, if the string is UTF-8 then you won't have problems with internationalisation etc. or someone feeding you a file with a Japanese name. But only UTF-8, and there's no point using UTF-8 when everything else uses UTF-16 - probably including wherever you got the string from in the first place.
    – Rup
    Dec 15, 2011 at 11:08
  • @Rup: so know we know that you prefer UTF16. For your info, Windows treats filenames as opaque arrays of UTF-16 characters. Note also that UTF-16 is still a variable-length character encoding; it doesn't actually buy you much over UTF-8. I would have understood if you argued UCS-2 (fixed-length characters) for simplicity of implementation, but then again, windows treats it as UCS-16 anyway
    – sehe
    Dec 15, 2011 at 11:14
  • 1
    why reinvent the wheel, dear colleagues? Use libraries for that that have been tested and written by people who might know what they're doing. Jun 3, 2014 at 5:54

13 Answers 13

28

The initialisation is incorrect as you need to escape the backslashes:

string filename = "C:\\MyDirectory\\MyFile.bat";

To extract the directory if present:

string directory;
const size_t last_slash_idx = filename.rfind('\\');
if (std::string::npos != last_slash_idx)
{
    directory = filename.substr(0, last_slash_idx);
}
2
  • it's the answer only for the part, which is 'In this example, I should get...'. For a correct solution, a path handling library or an OS call should be used. Jun 3, 2014 at 5:56
  • 5
    Fails if the filename (legitimately) uses forward slashes. Also fails to get the (absolute) directory if the filename is relative. Also relies on encoding being set correctly. I wouldn't flag this as "correct" when there's Offirmo's (portable) Boost solution.
    – DevSolar
    Jun 3, 2014 at 5:57
26

The quick and dirty:

Note that you must also look for / because it is allowed alternative path separator on Windows

#include <string>
#include <iostream>

std::string dirnameOf(const std::string& fname)
{
     size_t pos = fname.find_last_of("\\/");
     return (std::string::npos == pos)
         ? ""
         : fname.substr(0, pos);
}

int main(int argc, const char *argv[])
{
     const std::string fname = "C:\\MyDirectory\\MyFile.bat";

     std::cout << dirnameOf(fname) << std::endl;
}
0
19

Use the Boost.filesystem parent_path() function.

Ex. argument c:/foo/bar => c:/foo

More examples here : path decomposition table and tutorial here.

2
  • 3
    Not everyone uses boost.
    – Craig B
    May 27, 2020 at 22:40
  • IIANM, this doesn't work when the path is a filename-only (i.e. you get an empty path).
    – einpoklum
    May 13, 2021 at 10:26
15

C++17 provides std::filesystem::path. It may be available in C++11 in ; link with -lstdc++fs. Note the function does not validate the path exists; use std::filesystem::status to determine type of file (which may be filetype::notfound)

1
  • Great answer IF a person is using c++17. From what I see, that's where it was finally adopted.
    – Craig B
    May 27, 2020 at 22:46
13

The MFC way;

#include <afx.h>

CString GetContainingFolder(CString &file)
{
    CFileFind fileFind;
    fileFind.FindFile(file);
    fileFind.FindNextFile();
    return fileFind.GetRoot();
}

or, even simpler

CString path(L"C:\\my\\path\\document.txt");
path.Truncate(path.ReverseFind('\\'));
5
11

Since C++17 you can use std::filesystem::parent_path:

#include <filesystem>
#include <iostream>

int main() {
    std::string filename = "C:\\MyDirectory\\MyFile.bat";
    std::string directory = std::filesystem::path(filename).parent_path().u8string();
    std::cout << directory << std::endl;
}
1
  • When working with files name I have found it to be very convenient to use the raw strings syntax mostly because it is less error prone and easier on the eyes. R"(C:\MyDirectory\MyFile.bat)";
    – pmw1234
    Feb 5 at 14:46
6

As Question is old but I would like to add an answer so that it will helpful for others.
in Visual c++ you can use CString or char array also

CString filename = _T("C:\\MyDirectory\\MyFile.bat");  
PathRemoveFileSpec(filename); 

OUTPUT:

C:\MyDirectory

Include Shlwapi.h in your header files.

MSDN LINK here you can check example.

3
  • This code doesn't compile. Check Andrew Kozlov's answer
    – OneWorld
    Nov 26, 2018 at 13:29
  • Lot's of c++ is on systems that don't have CString.
    – Craig B
    May 27, 2020 at 22:42
  • This is not the greatest example of the function's usage. It takes a pointer to a mutable char array as input parameter, ATL CStrings just happen to implicitly convert to that, but the function is usable with any C-style string. BOOL PathRemoveFileSpec(char* pszPath)
    – Vinz
    Oct 16, 2023 at 18:35
5

A very simple cross-platform solution (as adapted from this example for string::find_last_of):

std::string GetDirectory (const std::string& path)
{
    size_t found = path.find_last_of("/\\");
    return(path.substr(0, found));
}

This works for both cases where the slashes can be either backward or forward pointing (or mixed), since it merely looks for the last occurrence of either in the string path.

However, my personal preference is using the Boost::Filesystem libraries to handle operations like this. An example:

std::string GetDirectory (const std::string& path)
{
    boost::filesystem::path p(path);
    return(p.parent_path().string());
}

Although, if getting the directory path from a string is the only functionality you need, then Boost might be a bit overkill (especially since Boost::Filesystem is one of the few Boost libraries that aren't header-only). However, AFIK, Boost::Filesystem had been approved to be included into the TR2 standard, but might not be fully available until the C++14 or C++17 standard (likely the latter, based on this answer), so depending on your compiler (and when you're reading this), you may not even need to compile these separately anymore since they might be included with your system already. For example, Visual Studio 2012 can already use some of the TR2 filesystem components (according to this post), though I haven't tried it since I'm still using Visual Studio 2010...

5

You can use the _spliltpath function available in stdlib.h header. Please refer to this link for the same.

http://msdn.microsoft.com/en-us/library/aa273364%28v=VS.60%29.aspx

1
  • Given the lack of a C#-like dirname function, this is absolutely the best method, as it doesn't depend on the format of the path.
    – Dana
    Aug 17, 2017 at 14:25
1

This is proper winapi solution:

CString csFolder = _T("c:\temp\file.ext");
PathRemoveFileSpec(csFolder.GetBuffer(0));
csFolder.ReleaseBuffer(-1);
2
  • "This function is deprecated. We recommend the use of the PathCchRemoveFileSpec function in its place." Otherwise this is the proper answer, so a +1 from me
    – YePhIcK
    Mar 15, 2017 at 10:39
  • OP didn't mention winapi.
    – Craig B
    May 27, 2020 at 22:44
1

If you have access to Qt, you can also do it like this:

std::string getDirectory(const std::string & file_path)
{
   return QFileInfo(QString(file_path)).absolutePath().toStdString();
}
0

The way of Beetle)

#include<tchar.h>

int GetDir(TCHAR *fullPath, TCHAR *dir) {
    const int buffSize = 1024;

    TCHAR buff[buffSize] = {0};
    int buffCounter = 0;
    int dirSymbolCounter = 0;

    for (int i = 0; i < _tcslen(fullPath); i++) {
        if (fullPath[i] != L'\\') {
            if (buffCounter < buffSize) buff[buffCounter++] = fullPath[i];
            else return -1;
        } else {
            for (int i2 = 0; i2 < buffCounter; i2++) {
                dir[dirSymbolCounter++] = buff[i2];
                buff[i2] = 0;
            }

            dir[dirSymbolCounter++] = fullPath[i];
            buffCounter = 0;
        }
    }

    return dirSymbolCounter;
}

Using :

TCHAR *path = L"C:\\Windows\\System32\\cmd.exe";
TCHAR  dir[1024] = {0};

GetDir(path, dir);
wprintf(L"%s\n%s\n", path, dir);
0

You can simply search the last "\" and then cut the string:

string filePath = "C:\MyDirectory\MyFile.bat" 
size_t slash = filePath.find_last_of("\");
string dirPath = (slash != std::string::npos) ? filePath.substr(0, slash) : filePath;

make sure in Linux to search "/" instead of "\":

size_t slash = filePath.find_last_of("/");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.