从文件名获取目录名称

我有一个文件名(C:\文件夹\ foo.txt),我需要检索非托pipeC ++中的文件夹名称(C:\文件夹)。 在C#中,我会做这样的事情:

string folder = new FileInfo("C:\folder\foo.txt").DirectoryName; 

有没有一个函数可以用于非托pipeC ++从文件名中提取path?

有一个标准的Windows函数, PathRemoveFileSpec 。 如果您只支持Windows 8及更高版本,则强烈build议使用PathCchRemoveFileSpec 。 除其他改进之外,它不再限制为MAX_PATH (260)个字符。

使用Boost.Filesystem:

 boost::filesystem::path p("C:\\folder\\foo.txt"); boost::filesystem::path dir = p.parent_path(); 

来自http://www.cplusplus.com/reference/string/string/find_last_of/的示例;

 // string::find_last_of #include <iostream> #include <string> using namespace std; void SplitFilename (const string& str) { size_t found; cout << "Splitting: " << str << endl; found=str.find_last_of("/\\"); cout << " folder: " << str.substr(0,found) << endl; cout << " file: " << str.substr(found+1) << endl; } int main () { string str1 ("/usr/bin/man"); string str2 ("c:\\windows\\winhelp.exe"); SplitFilename (str1); SplitFilename (str2); return 0; } 

使用boost :: filesystem。 无论如何,它将被纳入下一个标准,所以你也可以习惯它。

为什么它必须如此复杂?

 #include <windows.h> int main(int argc, char** argv) // argv[0] = C:\dev\test.exe { char *p = strrchr(argv[0], '\\'); if(p) p[0] = 0; printf(argv[0]); // argv[0] = C:\dev } 

根据cppreference.com,对于C ++ 17 / 1z,使用parent_path方法对std::experimental::filesystem::path进行实验性的头文件库支持。

 #include <iostream> #include <experimental/filesystem> namespace fs = std::experimental::filesystem; int main() { for(fs::path p : {"/var/tmp/example.txt", "/", "/var/tmp/."}) std::cout << "The parent path of " << p << " is " << p.parent_path() << '\n'; } 

可能的输出:

 The parent path of "/var/tmp/example.txt" is "/var/tmp" The parent path of "/" is "" The parent path of "/var/tmp/." is "/var/tmp" 

_splitpath是一个不错的CRT解决scheme。

在这方面,标准C ++对你来说不会有太大的帮助,因为path名是特定于平台的。 您可以手动分析string(如glowcoder的答案),使用操作系统设施(例如http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx ),或者可能最好的方法,你可以使用像boost :: filesystem这样的第三方文件系统库。

我很惊讶没有人提到Posix的标准方式

请使用basename / dirname结构。

男人的基本名字

只需使用这个:ExtractFilePath(your_path_file_name)