boom
boom

Reputation: 6166

Getting file extension in C language

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.

Upvotes: 7

Views: 11038

Answers (4)

paxdiablo
paxdiablo

Reputation: 881453

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]

Upvotes: 10

Ofek Shilon
Ofek Shilon

Reputation: 16129

There's a portable CRT solution: _splitpath.

In windows there's also an undocumented shell32 API called PathGetExtension, but that's evil in so many ways that I probably shouldn't have noted that.

Upvotes: 2

Shrikant
Shrikant

Reputation: 39

Use strchr First array member will give you filename Second array member will give you extension

Upvotes: -1

Jonathan Leffler
Jonathan Leffler

Reputation: 753735

Probably:

#include <string.h>

char *extn = strrchr(filename, '.');

That will give you a pointer to the period of the extension, or a null pointer if there is no extension. You might need to do some more due diligence to ensure that there isn't a slash after the dot, amongst other things.

Upvotes: 6

Related Questions