Linux C: 从指定路径中获取文件名

Linux 或者 android 下可以通过  strrchr() 函数从指定路径中获取文件名,

这个函数的作用是:查找字符串中最后一个出现的指定字符,它还有一个对应函数  strchr , 可用于: 查找字符串第一个出现的指定字符。使用这两个函数前,需要 #include <string.h>

例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void *GetFileName1(char *filePath)
{
    // int len = strlen(filePath);

    char ch = '\\'; // 其中一个反斜杠是转义字符
    char *q = strrchr(filePath, ch) + 1;    // 注意这里要+1, 否则输出是:\Photoshop5.exe

    return q;
}


void *GetFileName2(char *filePath)
{
    char ch = '/';
    char *q = strrchr(filePath, ch) + 1;

    return q;
}


int main()
{

    char p1[] = "D:\\SoftWare\\Adobe\\Photoshop5.exe";
    printf("%s\n", GetFileName1(p1));

    printf("-----------------------------------\n");

    char p2[] = "/mnt/sdcard/media/HAHAWTF.mp3";
    printf("%s\n", GetFileName2(p2));

    getchar();

    return 0;
}

运行:

Photoshop5.exe
-----------------------------------
HAHAWTF.mp3

 

posted @ 2020-12-08 10:37  夜行过客  阅读(3508)  评论(0编辑  收藏  举报