How to get file extension from string in C++

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

    If you consider the extension as the last dot and the possible characters after it, but only if they don't contain the directory separator character, the following function returns the extension starting index, or -1 if no extension found. When you have that you can do what ever you want, like strip the extension, change it, check it etc.

    long get_extension_index(string path, char dir_separator = '/') {
        // Look from the end for the first '.',
        // but give up if finding a dir separator char first
        for(long i = path.length() - 1; i >= 0; --i) {
            if(path[i] == '.') {
                return i;
            }
            if(path[i] == dir_separator) {
                return -1;
            }
        }
        return -1;
    }
    

提交回复
热议问题