C++版_splitpath
来源:互联网 发布:mac office 2016好用吗 编辑:程序博客网 时间:2024/05/21 11:08
今天写程序时遇到给定文件全路径求文件路径,即去掉后面的文件名称。
用MFC比较容易实现,可以用如下的示例得到
TCHAR szPath[MAX_PATH];
if( !GetModuleFileName(NULL, szPath, MAX_PATH ))
{
printf("GetModuleFileName failed (%d)/n", GetLastError());
return _T("");
}
CString strPath(szPath);
int nPos = strPath.ReverseFind('//');
strPath = strPath.Left(nPos + 1);
或者
TCHAR szPathName[MAX_PATH] = { 0 };
TCHAR szDrive[_MAX_DRIVE] = { 0 };
TCHAR szDir[_MAX_DIR] = { 0 };
TCHAR szFname[_MAX_FNAME] = { 0 };
TCHAR szExt[_MAX_EXT] = { 0 };
(void)::GetModuleFileName( NULL, szPathName, MAX_PATH );
_splitpath( szPathName, szDrive, szDir, szFname, szExt );
但用指针操作,更能锻练C++的功力,在网上搜索了一段代码,发觉下面的程序写的很精巧。摘录如下:
#include "stdio.h"
#include "conio.h"
void splitname(const char *szfullfilename, char *szpathname, char *szfilename, char *szextname);
int main(void)
{
char szfullfilename[255] = "C://windows//help.txt";
char szpathname[255];
char szfilename[255];
char szextname[255];
splitname(szfullfilename, szpathname, szfilename, szextname);
printf("%s/n", szfullfilename);
printf("path: %s/n", szpathname);
printf("file: %s/n", szfilename);
printf("ext: %s/n", szextname);
}
void splitname(const char *szfullfilename, char *szpathname, char *szfilename, char *szextname)
{
int i, j;
i = 0;
while (szfullfilename[i] != '/0')
i++;
while (szfullfilename[i] != '.')
i--;
j = 0;
i++;
while((szextname[j] = szfullfilename[i]) != '/0')
{
i++;
j++;
}
i -= j;
while (szfullfilename[i] != '//')
i--;
for (j = 0; j <= i; j++)
{
szpathname[j] = szfullfilename[j];
}
szpathname[j] = '/0';
j = 0;
i++;
while((szfilename[j] = szfullfilename[i]) != '/0')
{
i++;
j++;
}
}
上面的程序,是从后向前分析的,先找出后缀名,再找出路径名,最后分析文件名。
根据上面的程序,我自己改写了,从前向后分析,先得到路径名,再得到后缀名,最后得到文件名。
改写程序如下:
void splitname(const char *szfullfilename, char *szpathname, char *szfilename, char *szextname)
{
int i, j;
i = 0;
while (szfullfilename[i] != '/0')
i++;
while (szfullfilename[i] != '//')
i--;
for (j = 0; j <i; j++)
{
szpathname[j] = szfullfilename[j];
}
szpathname[j] = '/0';
j = 0;
i++;
while((szfilename[j] = szfullfilename[i]) != '/0')
{
i++;
j++;
}
while (szfullfilename[i] != '.')
i--;
j = 0;
i++;
while((szextname[j] = szfullfilename[i]) != '/0')
{
j++;
i++;
}
}
过程基本是复制的。
- C++版_splitpath
- C/C++ 之 _splitpath 获取文件路径
- _splitpath,_makepath分析路径
- 分割文件名 _splitpath() 函数
- _splitpath,_makepath分析路径
- 函数_splitpath用法
- _splitpath 分解路径
- _splitpath,_makepath分析路径
- 分割文件名 _splitpath() 函数
- _makepath 和_splitpath
- _splitpath, _wsplitpath 分割路径
- _splitpath,_makepath分析路径
- _splitpath,_makepath分析路径
- _makepath 和 _splitpath
- _splitpath函数使用
- _splitpath, _wsplitpath 分割路径
- [转]分割文件名 _splitpath() 函数
- 分析路径参数函数_splitpath
- typedef用法
- 12.8日iostream最后一天学习
- 我的j2me环境配置与第一个程序的建立
- Silverlight学习笔记--多媒体
- 芯片
- C++版_splitpath
- 开源BI平台Openi的开发数据仓库系统(下)
- JSF session的用法
- 【转】毕业5年决定你的命运
- wrap用法
- java获取中文拼音
- FindFirstStore函数 按扇区读取Windows Mobile的数据
- oracle10g数据导入导入导出
- session在何时被创建