How to get file extension from string in C++

前端 未结 25 2497
迷失自我
迷失自我 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:27

    Here's a function that takes a path/filename as a string and returns the extension as a string. It is all standard c++, and should work cross-platform for most platforms.

    Unlike several other answers here, it handles the odd cases that windows' PathFindExtension handles, based on PathFindExtensions's documentation.

    wstring get_file_extension( wstring filename )
    {
        size_t last_dot_offset = filename.rfind(L'.');
        // This assumes your directory separators are either \ or /
        size_t last_dirsep_offset = max( filename.rfind(L'\\'), filename.rfind(L'/') );
    
        // no dot = no extension
        if( last_dot_offset == wstring::npos )
            return L"";
    
        // directory separator after last dot = extension of directory, not file.
        // for example, given C:\temp.old\file_that_has_no_extension we should return "" not "old"
        if( (last_dirsep_offset != wstring::npos) && (last_dirsep_offset > last_dot_offset) )
            return L"";
    
        return filename.substr( last_dot_offset + 1 );
    }
    

提交回复
热议问题