linux c实现的提取文件名的小程序

/*@author etangyushan
 *工作中很多时候会和文件名打交道,有时候只需要文件名称,就写了这么一个小程序
 *这个函数实现了把一个文件的绝对路径和后缀去除,只留下文件名的功能
 * */

#include <stdio.h>

#include <stdlib.h>

#include <string.h>



//找到最后的slash(/)

int last_mark (char *str, char mark)

{

    int site = 0;  

    int count = 0;

    while (site <= strlen(str))

    {

        if (str[site++] == mark)

        {

         count = site; 

        }

    }

    return count;

}



//找到第一个dot(.)

int first_mark (char *str, char mark, int num)

{

    int count = num;

    while (1)  

    {

        if (str[count++] == mark)

        {

            break;

        }

    }

    return count; 

}



/* 从文件全名中把文件名提取出来,有后缀 */

int substr_suffix (char *srcstr, char *decstr, int slash)

{

    int i = 0;

    int size = strlen(srcstr);

    for (i=0; i<size; i++)

    {

        decstr[i] = srcstr[slash++];

    }

}



/* 从文件全名中把文件名提取出来,去除后缀 */

int substr (char *srcstr, char *decstr, int lastslash, int firstdot)

{

    int i = 0;

    //printf("last=%d,first=%d\n", lastslash, firstdot);

    //printf("size=%d\n", firstdot-lastslash);

    int size = firstdot-lastslash-1;

    for (i=0; i<size; i++)

    {

        //printf("...%c...\n",srcstr[lastslash]);

        decstr[i] = srcstr[lastslash++];

    }

}



//测试

int main()

{

    char *file = "/root/etc/init.d/myte123456789abcedefadfaefsa1234.c";

    char filename[256] = {};

    char filename_nosuffix[256] = {};



    int lastnum = last_mark (file, '/');

    int firstnum = first_mark (file, '.', lastnum);



    substr_suffix (file, filename, lastnum);

    printf ("filename = %s\n", filename);



    substr (file, filename_nosuffix, lastnum, firstnum);

    printf ("filename no suffix = %s\n", filename_nosuffix);

}

 

你可能感兴趣的:(linux)