【问题标题】:How to get the folder and file part of a complete path? [duplicate]如何获取完整路径的文件夹和文件部分? [复制]
【发布时间】:2015-03-01 10:15:58
【问题描述】:

我有一个完整的路径,例如 /a/b/c/text.txt

如何使用 c++ 获取 /a/b/c 和 text.txt?喜欢使用一些标准库函数。

我打算用

子字符串和 find_last_of

【问题讨论】:

  • 你有没有尝试过任何东西
  • 我正在尝试使用一些 std::string 方法,但想知道一开始是否有错误的方向
  • 特别是我想避免使用 Boost 库,也许。我知道 boost 可能支持路径方法。
  • stl 没有任何东西可以处理文件路径。升压确实如此。如果你不能使用嘘声,你必须自己做。应该不会很困难。
  • 你可以看看这个答案:stackoverflow.com/a/3071694/2082964

标签: c++ c++11


【解决方案1】:

使用find_last_of - http://www.cplusplus.com/reference/string/string/find_last_of/

应该和 substr 一起为你推测一个解决方案

【讨论】:

    【解决方案2】:

    您可以尝试以下方法:

    std::string path = "/a/b/c/text.txt";
    size_t lastSlash = path.rfind("/");
    if (lastSlash != std::string::npos){
        std::string filename = path.substr(lastSlash + 1);
        std::string folder = path.substr(0, lastSlash);
    }
    

    请注意,这仅适用于正斜杠。

    【讨论】:

    • 我个人更喜欢使用find_last_of,因为它涵盖了“/”和“\”
    • 为什么不根据平台覆盖适当的。
    • 好的,你可以这样做。我刚刚意识到他们有一个与我在 cplusplus.com 上使用 find_last_of 的示例基本相同的示例:cplusplus.com/reference/string/string/find_last_of 某些平台(如 Windows)同时使用两者。
    【解决方案3】:

    基于重复(stackoverflow.com/a/3071694/2082964),我认为以下解决了问题,

    请注意,取决于您是否需要尾随/;对于我的问题,我需要,所以我稍微修改了一下。

     // 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+1) << 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;
        }
    

    【讨论】:

    • 您应该对来自find_last_of的返回值进行错误检查
    • @Praetorian,你是什么意思?如果find_last_of没有找到,它会返回-1,对吧?
    • 它返回string::npos(即-1)。如果发生这种情况,后续的substr 调用将返回不正确的结果。好吧,也许不正确。 folder 子字符串将为空,而 file 子字符串将是整个输入,这可能是也可能不是您想要的行为。
    • 你应该这样做,但这不是我的意思。我编辑了我之前的评论,以解释为什么我认为它可能不是您想要的结果,但看起来确实如此,因此您的解决方案有效。
    • 这是来自cplusplus.com/reference/string/string/find_last_of的剪切粘贴吗?
    猜你喜欢
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2013-07-08
    • 2015-06-15
    • 2012-10-20
    • 2011-07-10
    • 1970-01-01
    相关资源
    最近更新 更多