How to get file extension from string in C++

前端 未结 25 2445
迷失自我
迷失自我 2020-11-30 22:35

Given a string \"filename.conf\", how to I verify the extension part?

I need a cross platform solution.

25条回答
  •  一生所求
    2020-11-30 23:24

    With C++17 and its std::filesystem::path::extension (the library is the successor to boost::filesystem) you would make your statement more expressive than using e.g. std::string.

    #include 
    #include  // C++17
    namespace fs = std::filesystem;
    
    int main()
    {
        fs::path filePath = "my/path/to/myFile.conf";
        if (filePath.extension() == ".conf") // Heed the dot.
        {
            std::cout << filePath.stem() << " is a valid type."; // Output: "myFile is a valid type."
        }
        else
        {
            std::cout << filePath.filename() << " is an invalid type."; // Output: e.g. "myFile.cfg is an invalid type"
        }
    }
    

    See also std::filesystem::path::stem, std::filesystem::path::filename.

提交回复
热议问题