Get a file name from a path

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

    You can also use the shell Path APIs PathFindFileName, PathRemoveExtension. Probably worse than _splitpath for this particular problem, but those APIs are very useful for all kinds of path parsing jobs and they take UNC paths, forward slashes and other weird stuff into account.

    wstring filename = L"C:\\MyDirectory\\MyFile.bat";
    wchar_t* filepart = PathFindFileName(filename.c_str());
    PathRemoveExtension(filepart); 
    

    http://msdn.microsoft.com/en-us/library/windows/desktop/bb773589(v=vs.85).aspx

    The drawback is that you have to link to shlwapi.lib, but I'm not really sure why that's a drawback.

    0 讨论(0)
  • 2020-12-01 00:35

    The Simplest way in C++17 is:

    use the #include <filesystem> and filename() for filename with extension and stem() without extension.

        #include <iostream>
        #include <filesystem>
        namespace fs = std::filesystem;
    
        int main()
        {
            string filename = "C:\\MyDirectory\\MyFile.bat";
    
        std::cout << fs::path(filename).filename() << '\n'
            << fs::path(filename).stem() << '\n'
            << fs::path("/foo/bar.txt").filename() << '\n'
            << fs::path("/foo/bar.txt").stem() << '\n'
            << fs::path("/foo/.bar").filename() << '\n'
            << fs::path("/foo/bar/").filename() << '\n'
            << fs::path("/foo/.").filename() << '\n'
            << fs::path("/foo/..").filename() << '\n'
            << fs::path(".").filename() << '\n'
            << fs::path("..").filename() << '\n'
            << fs::path("/").filename() << '\n';
        }
    

    output:

    MyFile.bat
    MyFile
    "bar.txt"
    ".bar"
    "."
    "."
    ".."
    "."
    ".."
    "/"
    

    Reference: cppreference

    0 讨论(0)
  • 2020-12-01 00:36

    From C++ Docs - string::find_last_of

    #include <iostream>       // std::cout
    #include <string>         // 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
    
    0 讨论(0)
提交回复
热议问题