如何最简单地获取文件所在的目录?我正在使用这个来查找工作目录。
string filename = "C:\MyDirectory\MyFile.bat"
在这个示例中,我应该得到"C:\MyDirectory"。
如何最简单地获取文件所在的目录?我正在使用这个来查找工作目录。
string filename = "C:\MyDirectory\MyFile.bat"
在这个示例中,我应该得到"C:\MyDirectory"。
这个初始化是不正确的,因为你需要转义反斜杠:
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);
}
简述:
请注意,因为在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;
}
C++17提供了std::filesystem::path。在C++11中可能需要链接-lstdc++fs才能使用该函数。请注意,该函数不会验证路径是否存在;使用std::filesystem::status确定文件类型(可能是filetype::notfound)。
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('\\'));
CString::Left
怎么样?https://msdn.microsoft.com/zh-cn/library/ms928948.aspx - SteztricC++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;
}
虽然这个问题比较老,但我想添加一个答案以便于对其他人有所帮助。
在Visual C++中,您可以使用CString或字符数组。
CString filename = _T("C:\\MyDirectory\\MyFile.bat");
PathRemoveFileSpec(filename);
输出:
C:\MyDirectory
在您的头文件中包含Shlwapi.h
。
MSDN链接,这里您可以查看示例。
BOOL PathRemoveFileSpec(char* pszPath)
- undefined您可以使用stdlib.h头文件中提供的_spliltpath函数。有关详细信息,请参阅此链接。
http://msdn.microsoft.com/en-us/library/aa273364%28v=VS.60%29.aspx
以下是一个非常简单的跨平台方案(从string::find_last_of
的这个示例进行了调整):
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库之一)。不过,据我所知,Boost::Filesystem已经被批准包含在TR2标准中,但可能要等到C++14或C++17标准(基于 这篇文章 的说法)才能完全使用,所以根据你的编译器(以及你目前读到的时间),你可能不再需要单独编译它们,因为它们可能已经随你的系统一起提供了。例如,Visual Studio 2012已经可以使用某些TR2文件系统组件(根据 这篇文章 的说法),不过我还没试过,因为我仍在使用Visual Studio 2010...
CString csFolder = _T("c:\temp\file.ext");
PathRemoveFileSpec(csFolder.GetBuffer(0));
csFolder.ReleaseBuffer(-1);