How to get file extension from string in C++

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

    You can use strrchr() to find last occurence of .(dot) and get .(dot) based extensions files. Check the below code for example.

    #include<stdio.h>
    
    void GetFileExtension(const char* file_name) {
    
        int ext = '.';
        const char* extension = NULL;
        extension = strrchr(file_name, ext);
    
        if(extension == NULL){
            printf("Invalid extension encountered\n");
            return;
        }
    
        printf("File extension is %s\n", extension);
    }
    
    int main()
    {
        const char* file_name = "c:\\.directoryname\\file.name.with.too.many.dots.ext";
        GetFileExtension(file_name);
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题