从文件路径c ++获取目录

时间:2011-12-15 10:40:41

标签: c++ visual-c++

获取文件所在目录的最简单方法是什么?我正在使用它来查找工作目录。

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

在这个例子中,我应该得到“C:\ MyDirectory”。

12 个答案:

答案 0 :(得分:17)

使用Boost.filesystem parent_path()函数。

实施例。参数 c:/ foo / bar => C:/富

此处有更多示例:path decomposition table和教程here

答案 1 :(得分:16)

快速而肮脏:

请注意,必须也会查找/,因为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;
}

答案 2 :(得分:15)

初始化不正确,因为您需要转义反斜杠:

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

提取目录(如果存在):

string directory;
const size_t last_slash_idx = filename.rfind('\\');
if (std::string::npos != last_slash_idx)
{
    directory = filename.substr(0, last_slash_idx);
}

答案 3 :(得分:12)

MFC方式;

#include <afx.h>

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

或者,甚至更简单

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

答案 4 :(得分:5)

您可以使用stdlib.h头文件中提供的_spliltpath函数。请参阅此链接。

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

答案 5 :(得分:4)

由于问题已经过时,但我想添加一个答案,以便对其他人有所帮助 在Visual c + +中,您也可以使用CString或char数组

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

<强>输出:

     

C:\ mydirectory中

在您的标头文件中包含Shlwapi.h

MSDN LINK,您可以查看示例。

答案 6 :(得分:3)

一个非常简单的跨平台解决方案(改编自string::find_last_of的{​​{3}}):

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

这适用于斜杠可以向后或向前指向(或混合)的两种情况,因为它只是查找字符串path中最后一次出现的斜杠。

但是,我的个人偏好是使用Boost :: Filesystem库来处理这样的操作。一个例子:

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

虽然,如果从字符串获取目录路径是你需要的唯一功能,那么Boost可能有点过分(特别是因为Boost :: Filesystem是少数几个不仅仅是头文件的Boost库之一)。但是,AFIK,Boost :: Filesystem已被批准包含在TR2标准中,但在C ++ 14或C ++ 17标准之前可能无法完全可用(可能是后者,基于this example) ,因此,根据您的编译器(以及您何时阅读本文),您可能甚至不需要再单独编译它们,因为它们可能已经包含在您的系统中。例如,Visual Studio 2012已经可以使用一些TR2文件系统组件(根据this answer),虽然我还没有尝试过,因为我还在使用Visual Studio 2010 ...

答案 7 :(得分:2)

这是正确的winapi解决方案:

CString csFolder = _T("c:\temp\file.ext");
PathRemoveFileSpec(csFolder.GetBuffer(0));
csFolder.ReleaseBuffer(-1);

答案 8 :(得分:1)

C ++ 17提供了std::filesystem::path。它可能在C ++ 11中可用;与-lstdc ++ fs链接。注意,该函数不会验证路径是否存在;使用std :: filesystem :: status确定文件类型(可能是filetype :: notfound)

答案 9 :(得分:1)

从 C++17 开始,您可以使用 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;
}

答案 10 :(得分:0)

甲壳虫的方式)

#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;
}

使用:

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

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

答案 11 :(得分:0)

您只需搜索最后一个“\”,然后剪切字符串:

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

确保在Linux中搜索“/”而不是“\”:

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

相关问题