get directory from file path c++

前端 未结 11 1407
梦如初夏
梦如初夏 2020-12-13 14:45

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.b         


        
相关标签:
11条回答
  • 2020-12-13 14:54

    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)

    0 讨论(0)
  • 2020-12-13 14:54

    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

    0 讨论(0)
  • 2020-12-13 14:56

    This is proper winapi solution:

    CString csFolder = _T("c:\temp\file.ext");
    PathRemoveFileSpec(csFolder.GetBuffer(0));
    csFolder.ReleaseBuffer(-1);
    
    0 讨论(0)
  • 2020-12-13 14:58

    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 讨论(0)
  • 2020-12-13 15:00

    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('\\'));
    
    0 讨论(0)
  • 2020-12-13 15:07

    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("/");

    0 讨论(0)
提交回复
热议问题