How to get file extension from string in C++

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

    For char array-type strings you can use this:

    #include 
    #include 
    
    int main()
    {
        char filename[] = "apples.bmp";
        char extension[] = ".jpeg";
    
        if(compare_extension(filename, extension) == true)
        {
            // .....
        } else {
            // .....
        }
    
        return 0;
    }
    
    bool compare_extension(char *filename, char *extension)
    {
        /* Sanity checks */
    
        if(filename == NULL || extension == NULL)
            return false;
    
        if(strlen(filename) == 0 || strlen(extension) == 0)
            return false;
    
        if(strchr(filename, '.') == NULL || strchr(extension, '.') == NULL)
            return false;
    
        /* Iterate backwards through respective strings and compare each char one at a time */
    
        for(int i = 0; i < strlen(filename); i++)
        {
            if(tolower(filename[strlen(filename) - i - 1]) == tolower(extension[strlen(extension) - i - 1]))
            {
                if(i == strlen(extension) - 1)
                    return true;
            } else
                break;
        }
    
        return false;
    }
    

    Can handle file paths in addition to filenames. Works with both C and C++. And cross-platform.

提交回复
热议问题