如何在C语言中从文件名获取文件扩展名(例如.tiff
)?
谢谢!
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("..."));
dot = strrchr(filename, '.');
之后,dot != NULL
意味着*dot == '.'
,因此您的测试应该简单地为if(dot)
。 - Chris Lutzrenamer.c:11: warning: incompatible implicit declaration of built-in function ‘strrchr’
。 - errorhandler~/.forward
中,“.forward” 不是扩展名。 - Steve Jessopstring.h
的strcmp()
例程。它将允许您将文件扩展名与给定字符串进行比较并执行某些操作,例如 if (strcmp(ext,"tiff") == 0) ...
。 - mabalenk用 strrchr
找到最后一个点号,然后向前移动一个字符
#include <stdio.h> /* printf */
#include <string.h> /* strrchr */
ext = strrchr(filename, '.');
if (!ext) {
/* no extension */
} else {
printf("extension is %s\n", ext + 1);
}
strrchr
函数来查找字符串中最后一个字符的位置,进而找到最后一个点号。然后,您可以将剩余的字符串读取为扩展名。这里有一个版本,它也适用于文件(或目录)路径:
#include <assert.h>
#include <string.h>
const char *FileSuffix(const char path[])
{
const char *result;
int i, n;
assert(path != NULL);
n = strlen(path);
i = n - 1;
while ((i > 0) && (path[i] != '.') && (path[i] != '/') && (path[i] != '\\')) {
i--;
}
if ((i > 0) && (i < n - 1) && (path[i] == '.') && (path[i - 1] != '/') && (path[i - 1] != '\\')) {
result = path + i;
} else {
result = path + n;
}
return result;
}
int main(void)
{
assert(strcmp(FileSuffix(""), "") == 0);
assert(strcmp(FileSuffix("."), "") == 0);
assert(strcmp(FileSuffix("f"), "") == 0);
assert(strcmp(FileSuffix("foo"), "") == 0);
assert(strcmp(FileSuffix("foo."), "") == 0);
assert(strcmp(FileSuffix(".foo"), "") == 0);
assert(strcmp(FileSuffix("foo.bar"), ".bar") == 0);
assert(strcmp(FileSuffix("foo/.bar"), "") == 0);
assert(strcmp(FileSuffix("foo\\.bar"), "") == 0);
assert(strcmp(FileSuffix("foo/bar.baz.qux"), ".qux") == 0);
assert(strcmp(FileSuffix("foo\\bar.baz.qux"), ".qux") == 0);
assert(strcmp(FileSuffix("foo.bar.baz/qux"), "") == 0);
assert(strcmp(FileSuffix("foo.bar.baz\\qux"), "") == 0);
return 0;
}