用C语言获取文件扩展名

boo*_*oom 6 c

假设有一个名为12345.jpg的文件.在C中,如何获取文件扩展名以便与某些文件扩展名进行比较?如果有任何内置功能,请告诉我.

pax*_*blo 9

这样做的功能,以及测试工具:

#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;
}
Run Code Online (Sandbox Code Playgroud)

运行此:

./program abc abc. abc.1 .xyz abc.def abc.def.ghi
Run Code Online (Sandbox Code Playgroud)

给你:

[abc] - > []
[abc.] - > [.]
[abc.1] - > [.1]
[.xyz] - > [.xyz]
[abc.def] - > [.def]
[abc.def.ghi] - > [.ghi]
Run Code Online (Sandbox Code Playgroud)


Jon*_*ler 5

大概:

#include <string.h>

char *extn = strrchr(filename, '.');
Run Code Online (Sandbox Code Playgroud)

这将为您提供指向扩展周期的指针,如果没有扩展名,则为空指针.您可能需要做更多的尽职调查,以确保点之后没有斜线,等等.

  • `strrchr(filename + 1,'.');`会处理像`.svn`这样的名字,它以点开头但没有扩展名. (3认同)