【问题标题】:c++ how to remove filename from path stringc ++如何从路径字符串中删除文件名
【发布时间】:2012-04-28 15:23:17
【问题描述】:

我有

const char *pathname = "..\somepath\somemorepath\somefile.ext";

如何转换成

"..\somepath\somemorepath"

?

【问题讨论】:

  • Boost 有一个不错的 filesystem::path 类...

标签: c++ string filesystems


【解决方案1】:

最简单的方法是使用std::string的成员函数find_last_of

string s1("../somepath/somemorepath/somefile.ext");
string s2("..\\somepath\\somemorepath\\somefile.ext");
cout << s1.substr(0, s1.find_last_of("\\/")) << endl;
cout << s2.substr(0, s2.find_last_of("\\/")) << endl;

此解决方案适用于正斜杠和反斜杠。

【讨论】:

【解决方案2】:

在 Windows 上使用 _splitpath(),在 Linux 上使用 dirname()

【讨论】:

    【解决方案3】:

    在 Windows 8 上,使用PathCchRemoveFileSpec,可以在Pathcch.h 中找到

    PathCchRemoveFileSpec 将删除路径中的最后一个元素,因此如果您将目录路径传递给它,最后一个文件夹将被删除。
    如果您想避免这种情况,并且不确定文件路径是否为目录,请使用PathIsDirectory

    PathCchRemoveFileSpec 在包含正斜杠的路径上的行为不符合预期。

    【讨论】:

      【解决方案4】:

      使用strrchr() 查找最后一个反斜杠并删除字符串。

      char *pos = strrchr(pathname, '\\');
      if (pos != NULL) {
         *pos = '\0'; //this will put the null terminator here. you can also copy to another string if you want
      }
      

      【讨论】:

      • 如果是正斜杠 (/) 怎么办?
      【解决方案5】:

      PathRemoveFileSpec(...) 你不需要 Windows 8。 您将需要包括 Shlwapi.h 和 Shlwapi.lib 但它们是winapi,所以你不需要任何特殊的SDK

      【讨论】:

        猜你喜欢
        • 2011-04-22
        • 2010-09-13
        • 1970-01-01
        • 2022-01-12
        • 2011-11-28
        • 1970-01-01
        • 2011-04-09
        • 2010-11-09
        • 1970-01-01
        相关资源
        最近更新 更多