C语言 在 C 中获取文件扩展名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5309471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting file extension in C
提问by errorhandler
How do you get a file extension (like .tiff) from a filename in C?
如何.tiff从 C 中的文件名获取文件扩展名(如)?
Thanks!
谢谢!
回答by ThiefMaster
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("..."));
回答by pmg
Find the last dot with strrchr, then advance 1 char
用 找到最后一个点strrchr,然后前进 1 个字符
#include <stdio.h> /* printf */
#include <string.h> /* strrchr */
ext = strrchr(filename, '.');
if (!ext) {
/* no extension */
} else {
printf("extension is %s\n", ext + 1);
}
回答by templatetypedef
You can use the strrchrfunction, 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.
您可以使用该strrchr函数搜索字符串中最后一次出现的字符,以找到最后一个点。从那里,您可以读取字符串的其余部分作为扩展名。

