Get a file name from a path

前端 未结 21 1573
面向向阳花
面向向阳花 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:36

    From C++ Docs - string::find_last_of

    #include        // std::cout
    #include          // std::string
    
    void SplitFilename (const std::string& str) {
      std::cout << "Splitting: " << str << '\n';
      unsigned found = str.find_last_of("/\\");
      std::cout << " path: " << str.substr(0,found) << '\n';
      std::cout << " file: " << str.substr(found+1) << '\n';
    }
    
    int main () {
      std::string str1 ("/usr/bin/man");
      std::string str2 ("c:\\windows\\winhelp.exe");
    
      SplitFilename (str1);
      SplitFilename (str2);
    
      return 0;
    }
    

    Outputs:

    Splitting: /usr/bin/man
     path: /usr/bin
     file: man
    Splitting: c:\windows\winhelp.exe
     path: c:\windows
     file: winhelp.exe
    

提交回复
热议问题