1. 需求
需要求 一个文件的绝对路径: e:\1\2\abc.dat 的路径或者文件名
如:e:\1\2\abc.dat
路径: e:\1\2
文件名:abc.dat
2. 代码实现
#include <stdio.h>
#include<string.h>
#define FILE_PATH_LENGTH 128
#define IN //表示参数是入参
#define OUT
void getacFilePath(IN char* pSrc, OUT char* pDst)
{
char* tmp = NULL;
char* pFileName = NULL;
int iStrLen = 0;
if(NULL == pSrc){
return ;
}
tmp = pSrc;
pFileName = (pFileName=strrchr(tmp,'\\')) ? pFileName : tmp;
iStrLen = pFileName-tmp;
//printf("iStrLen = %d \n",iStrLen);
strncpy(pDst,tmp, iStrLen);
pDst[iStrLen + 1] = '\0';
//printf("pDst = %s \n",pDst);
return ;
}
void getFileName(IN char* pSrc, IN int iSrcLen, OUT char* pDst)
{
char* tmp = NULL;
char* pFileName = NULL;
int iStrLen = 0;
if(NULL == pSrc){
return ;
}
tmp = pSrc;
(pFileName=strrchr(tmp,'\\')) ? pFileName+1 : tmp;
strcpy(pDst,pFileName+1);
//printf("getFileName pDst = %s \n", pDst);
//printf("getFileName pFileName = %s \n", pFileName);
return ;
}
int main()
{
printf("This is a program that can get file name and absolute path, start!\n");
char pPathName[FILE_PATH_LENGTH] = "e:\\1\\2\\abc.dat";
char acDstName[FILE_PATH_LENGTH];
char acDstPath[FILE_PATH_LENGTH];
memset(acDstName, 0, sizeof(acDstName));
memset(acDstPath, 0, sizeof(acDstPath));
printf("src pPathName: = %s \n", pPathName);
printf("src pPathName len: = %d \n\n", strlen(pPathName));
getFileName(pPathName, strlen(pPathName), acDstName);
printf("acDstName = %s \n", acDstName);
getacFilePath(pPathName, acDstPath);
printf("acDstPath = %s \n", acDstPath);
printf("This is a program that can get file name and absolute path, end!\n");
return 0;
}
结果: