Getting file extension in C

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("..."));

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);
}

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.

Tags:

C

String

File