所以我们有一个路径字符串/home/user/music/thomas.mp3
。
从该字符串中提取文件名(不带扩展名“thomas”)及其扩展名(“mp3”)的简单方法在哪里?文件名和扩展名的函数。我们手中只有 GNU libc。
<小时/>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILENAME_SIZE 256
char *filename(char *str) {
char *result;
char *last;
if ((last = strrchr(str, '.')) != NULL ) {
if ((*last == '.') && (last == str))
return str;
else {
result = (char*) malloc(MAX_FILENAME_SIZE);
snprintf(result, sizeof result, "%.*s", (int)(last - str), str);
return result;
}
} else {
return str;
}
}
char *extname(char *str) {
char *result;
char *last;
if ((last = strrchr(str, '.')) != NULL) {
if ((*last == '.') && (last == str))
return "";
else {
result = (char*) malloc(MAX_FILENAME_SIZE);
snprintf(result, sizeof result, "%s", last + 1);
return result;
}
} else {
return ""; // Empty/NULL string
}
}
最佳答案
使用basename获取文件名,然后您可以使用类似的方法来获取扩展名。
char *get_filename_ext(const char *filename) {
const char *dot = strrchr(filename, '.');
if(!dot || dot == filename) return "";
return dot + 1;
}
编辑: 尝试类似的东西。
#include <string.h>
#include <libgen.h>
static void printFileInfo(char *path) {
char *bname;
char *path2 = strdup(path);
bname = basename(path2);
printf("%s.%s\n",bname, get_filename_ext(bname));
free(path2);
}
关于c - 在C中提取文件名及其扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24975928/