Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting file extension in C language

Tags:

c

Say there is a file called 12345.jpg. In C, how can I get the file extension so that I can compare with some file extension? If there are any inbuilt functions, kindly please let me know.

like image 745
boom Avatar asked Jun 14 '10 06:06

boom


Video Answer


1 Answers

A function to do that, along with a test harness:

#include <stdio.h>
#include <string.h>

const char *getExt (const char *fspec) {
    char *e = strrchr (fspec, '.');
    if (e == NULL)
        e = ""; // fast method, could also use &(fspec[strlen(fspec)]).
    return e;
}

int main (int argc, char *argv[]) {
    int i;
    for (i = 1; i < argc; i++) {
        printf ("[%s] - > [%s]\n", argv[i], getExt (argv[i]));
    }
    return 0;
}

Running this with:

./program abc abc. abc.1 .xyz abc.def abc.def.ghi

gives you:

[abc] - > []
[abc.] - > [.]
[abc.1] - > [.1]
[.xyz] - > [.xyz]
[abc.def] - > [.def]
[abc.def.ghi] - > [.ghi]
like image 92
paxdiablo Avatar answered Oct 19 '22 16:10

paxdiablo