码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2014-05-07 18:02:20      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:int   string   文件   c   工作   name   

/*@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

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

标签:int   string   文件   c   工作   name   

原文地址:http://www.cnblogs.com/etangyushan/p/3709954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!