linux c实现的提取文件名的小程序
/*@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;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。