Get a file name from a path

前端 未结 21 1583
面向向阳花
面向向阳花 2020-11-30 23:55

What is the simplest way to get the file name that from a path?

string filename = \"C:\\\\MyDirectory\\\\MyFile.bat\"

In this example, I s

21条回答
  •  一整个雨季
    2020-12-01 00:23

    _splitpath should do what you need. You could of course do it manually but _splitpath handles all special cases as well.

    EDIT:

    As BillHoag mentioned it is recommended to use the more safe version of _splitpath called _splitpath_s when available.

    Or if you want something portable you could just do something like this

    std::vector splitpath(
      const std::string& str
      , const std::set delimiters)
    {
      std::vector result;
    
      char const* pch = str.c_str();
      char const* start = pch;
      for(; *pch; ++pch)
      {
        if (delimiters.find(*pch) != delimiters.end())
        {
          if (start != pch)
          {
            std::string str(start, pch);
            result.push_back(str);
          }
          else
          {
            result.push_back("");
          }
          start = pch + 1;
        }
      }
      result.push_back(start);
    
      return result;
    }
    
    ...
    std::set delims{'\\'};
    
    std::vector path = splitpath("C:\\MyDirectory\\MyFile.bat", delims);
    cout << path.back() << endl;
    

提交回复
热议问题