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

时间:2014-05-07 18:02:20   收藏:0   阅读:344

/*@author etangyushan
 *工作中很多时候会和文件名打交道,有时候只需要文件名称,就写了这么一个小程序
 *这个函数实现了把一个文件的绝对路径和后缀去除,只留下文件名的功能
 * */
#include <stdio.h>
#include <string.h>
#include <stdlib.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 (char *srcstr, char **decstr, int lastslash, int firstdot)
{
 int i = 0;
 //int ls = lastslash;
 char *str = *decstr;
 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++)
 {
  //str[i] = srcstr[ls++];
  printf("...%c...\n",srcstr[lastslash]);
  str[i] = srcstr[lastslash++];
 }
}

//测试
int main()
{
 char *file = "/root/etc/init.d/mytettttt.c";
 char *name = (char*)malloc(256);
 int lastnum = last_mark (file, ‘/‘);
 //printf ("lastnum=%d\n", lastnum);
 int firstnum = first_mark (file, ‘.‘, lastnum);
 //printf ("firstnum=%d\n", firstnum);
 substr (file, &name, lastnum, firstnum);
 printf ("name = %s\n", name);
 free(name);
 name = NULL;
}

linux c实现的提取文件名的小程序,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!