实现一个函数,取出一个全路径文件名中的文件名部分,函数原型如下:
/* [in] pszfullpath 全路径文件名
[out] pszpathname 接受全路径的缓冲区
[out] ncount 缓冲区的大小
*/
方法一: 常规方法
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int ExtractFilePath(char *pszfullpath,char *pszpathname,int ncount)
{
char kong[20]={0};
int num,i;
pszpathname=NULL;
printf("请输入文件全路径!\n");
pszfullpath = (char *)malloc(30*sizeof(char));
scanf("%s",pszfullpath);
num=strlen(pszfullpath); //计算全路径的长度
printf("%d\n",num);
ncount = 0;
for(i=0;i<num;i++)
{
if(pszfullpath[i] == '/') //如果遇到'/',则将ncount 赋值为零,即清空之前所存储的字符
{
printf("aaa\n");
ncount = 0;
}
else //否则就ncount ++
{
ncount++;
printf("ttt\n");
}
}
pszpathname = (char *)malloc(21*sizeof(char));
strcpy(pszpathname,pszfullpath+num-ncount);
printf("qqq\n");
if (pszpathname) //输出文件名
{
printf(" %s\n",pszpathname);
printf("the length is %d\n",ncount);
}
else
printf("The character was not found\n");
return 0;
}
int main()
{
char *pszfullpath1,*pszpathname1;
int ncount1;
ExtractFilePath(pszfullpath1,pszpathname1,ncount1);
return 0;
}
方法二: strrchr 函数的应用
#include <string.h>
#include <stdio.h>
int ExtractFilePath(char *pszfullpath,char *pszpathname,int ncount)
{
char string[20];
char c = '/';
pszfullpath=string;
printf("请输入文件全路径!\n");
scanf("%s",string);
pszpathname = strrchr(pszfullpath, c);
ncount = strlen(pszpathname+1);
printf("the length is : %d\n",ncount);
if (pszpathname)
{
printf("The character %c is at position: %s\n", c, pszpathname+1);
printf("the length is %d\n",ncount);
}
else
printf("The character was not found\n");
return 0;
}
int main()
{
char *pszfullpath1,*pszpathname1;
int ncount1;
ExtractFilePath(pszfullpath1,pszpathname1,ncount1);
return 0;
}