字符串:取出文件路径中的文件名和绝对路径

字符串:取出文件路径中的文件名和绝对路径

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;
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值