【问题标题】:Find only file name from full path of the file in vc++在 vc++ 中仅从文件的完整路径中查找文件名
【发布时间】:2012-07-17 11:22:22
【问题描述】:

假设有一个 CString 变量存储文件的完整路径。现在我只能从 if 中找到文件名。如何在 vc++ 中进行操作。

CString FileName = "c:\Users\Acer\Desktop\FolderName\abc.dll";

现在我只想要 abc.dll

【问题讨论】:

  • 你必须转义你的反斜杠
  • 我推荐here描述的函数decomposePath。

标签: c++ file visual-c++


【解决方案1】:

您可以使用PathFindFileName

请记住,您必须在路径字符串中转义 \ 字符!

【讨论】:

  • @Mark,为什么要转换?如果是 char* - ANSI 构建,则传递 char* !
【解决方案2】:

与上面已经说明的相同,但是由于您使用的是 MFC 框架,所以这将是实现它的方法。虽然这不会检查文件是否存在。

CString path= "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll";
CString fileName= path.Mid(path.ReverseFind('\\')+1);

【讨论】:

【解决方案3】:
std::string str = "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll";
std::string res = str.substr( str.find_last_of("\\") + 1 );

会给你“abs.dll”。

【讨论】:

  • 当您拥有具有所需功能的 CString 时,为什么要使用 std::string
【解决方案4】:

我会使用Boost::FileSystem 进行文件名操作,因为它了解名称的各个部分。你想要的函数是 filename()

如果您只是获取文件名,则可以使用 CString 函数来执行此操作。首先使用 ReverseFind 找到 ast 反斜杠,然后 Right 得到想要的字符串。

【讨论】:

    【解决方案5】:

    下面的代码演示了从完整路径中提取文件名

    #include <iostream>
    #include <cstdlib>
    #include <string>
    #include <algorithm>
    
    std::string get_file_name_from_full_path(const std::string& file_path)
    {
        std::string file_name;
    
        std::string::const_reverse_iterator it = std::find(file_path.rbegin(), file_path.rend(), '\\');
        if (it != file_path.rend())
        {
            file_name.assign(file_path.rbegin(), it);
            std::reverse(file_name.begin(), file_name.end());
            return file_name;
        }
        else
            return file_name;
    }
    
    int main()
    {
        std::string file_path = "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll";
        std::cout << get_file_name_from_full_path(file_path) << std::endl;
        return EXIT_SUCCESS;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      相关资源
      最近更新 更多