Search code examples
c++stringfilenamesfile-extension

How to get file extension from string in C++


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

I need a cross platform solution.


Solution

  • 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 <iostream>
    #include <filesystem> // 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: "myFile.cfg is an invalid type"
        }
    }
    

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