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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8518743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:42:27  来源:igfitidea点击:

get directory from file path c++

c++visual-c++

提问by nidhal

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

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

采纳答案by hmjd

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

回答by Offirmo

Use the Boost.filesystemparent_path() function.

使用Boost.filesystemparent_path() 函数。

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

前任。参数c:/foo/bar=> c:/foo

More examples here : path decomposition tableand tutorial here.

更多示例在这里:路径分解表和教程在这里

回答by sehe

The quick and dirty:

又快又脏:

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

请注意,您还必须查找,/因为它允许在 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;
}

回答by Steztric

The MFC way;

MFC方式;

#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('\'));

回答by gerardw

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)

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

回答by Ajit Vaze

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

您可以使用 stdlib.h 标头中提供的 _spliltpath 函数。请参阅此链接以获取相同信息。

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

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

回答by Himanshu

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

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

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

OUTPUT:

C:\MyDirectory

输出:

C:\我的目录

Include Shlwapi.hin your header files.

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

MSDN LINKhere you can check example.

MSDN LINKhere 您可以查看示例。

回答by Jared B.

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

一个非常简单的跨平台解决方案(如适于从本实施例中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.

这适用于斜线可以向后或向前(或混合)的两种情况,因为它仅查找 string 中最后一次出现的任何一个path

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

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

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

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

回答by Andrew Kozlov

This is proper winapi solution:

这是正确的 winapi 解决方案:

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

回答by Shady Sirhan

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 "\":

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

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

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