get directory from file path c++

前端 未结 11 1409
梦如初夏
梦如初夏 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:58

    The way of Beetle)

    #include
    
    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);
    

提交回复
热议问题