How do you get a file extension (like .tiff
开发者_运维知识库) from a filename in C?
Thanks!
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("..."));
Find the last dot with strrchr
, then advance 1 char
#include <stdio.h> /* printf */
#include <string.h> /* strrchr */
ext = strrchr(filename, '.');
if (!ext) {
/* no extension */
} else {
printf("extension is %s\n", ext + 1);
}
You can use the strrchr
function, 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.
Here is a version which works also for file (or directory) paths:
#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) && (path[i] == '.') && (path[i - 1] != '/') && (path[i - 1] != '\\')) {
result = path + i;
} else {
result = path + n;
}
return result;
}
int main(void)
{
assert(strcmp(FileSuffix("foo/bar.baz.qux"), ".qux") == 0);
assert(strcmp(FileSuffix("foo.bar.baz/qux"), "") == 0);
return 0;
}
精彩评论