Get a file name from a path

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

    The Simplest way in C++17 is:

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

        #include 
        #include 
        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

提交回复
热议问题