Getting file extension in C

前端 未结 3 655
慢半拍i
慢半拍i 2020-12-01 03:30

How do you get a file extension (like .tiff) from a filename in C?

Thanks!

相关标签:
3条回答
  • 2020-12-01 04:14

    You can use the strrchr function, which searches for the last occurrence of a character in a string, to find the final dot. From there, you can read off the rest of the string as the extension.

    0 讨论(0)
  • 2020-12-01 04:15

    Find the last dot with strrchr, then advance 1 char

    #include <stdio.h> /* printf */
    #include <string.h> /* strrchr */
    
    ext = strrchr(filename, '.');
    if (!ext) {
        /* no extension */
    } else {
        printf("extension is %s\n", ext + 1);
    }
    
    0 讨论(0)
  • 2020-12-01 04:21
    const char *get_filename_ext(const char *filename) {
        const char *dot = strrchr(filename, '.');
        if(!dot || dot == filename) return "";
        return dot + 1;
    }
    
    printf("%s\n", get_filename_ext("test.tiff"));
    printf("%s\n", get_filename_ext("test.blah.tiff"));
    printf("%s\n", get_filename_ext("test."));
    printf("%s\n", get_filename_ext("test"));
    printf("%s\n", get_filename_ext("..."));
    
    0 讨论(0)
提交回复
热议问题