相关分类 VC技巧 ->VC ->VCShare

已知文件名取文件所在目录

关键字 文件名取文件所在目录

已知文件名取文件所在目录?最简单的办法是从后向前查找"\\".但有时,文件名中没有"\\",这时就要先对文件名进行转换.具体代码如下:
CString GetPathName(const CString strPathFileName)
{
//取得经过处理后的文件名长度
int nLength = GetFullPathName(strPathFileName,0,NULL,NULL);
if( 0 == nLength )
return "" ;

//取得新文件名
CString strPathName ;
char * pszPathName = strPathName.GetBufferSetLength(nLength);
nLength = GetFullPathName(strPathFileName,nLength,pszPathName,NULL);
strPathName.ReleaseBuffer();
if( 0 == nLength )
return "" ;

//取得路径
int nPos = strPathName.ReverseFind('\\');
if(-1 == nPos )
return "";
strPathName = strPathName.Left(nPos);
return strPathName ;
}

测试代码如下:
void CMy2View::OnDraw(CDC* pDC)
{
CMy2Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);

CString strMess ;
CString strInput[] = {"1.txt","c:\\2.txt","d:3.txt","e:\\2/4.txt"};

int iCount = sizeof(strInput)/sizeof(strInput[0]) ;
for(int i = 0 ; i < iCount ; i++ )
{
CString strLine ;
CString strOutput = GetPathName(strInput[i]) ;
strLine.Format("文件名: %s\r\n对应文件夹 %s\r\n\r\n",strInput[i],strOutput);
strMess += strLine ;
}

CRect r ;
GetClientRect(r);
pDC->DrawText(strMess,&r,0);
}

结果如下:
文件名: 1.txt
对应文件夹 G:\TEST\2

文件名: c:\2.txt
对应文件夹 c:

文件名: d:3.txt
对应文件夹 D:

文件名: e:\2/4.txt
对应文件夹 e:\2


如果文件名标准,可以用_splitpath函数解析,示例代码如下:

char path_buffer[_MAX_PATH];
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];

_makepath( path_buffer, "c", "\\sample\\crt\\", "makepath", "c" );
_splitpath( path_buffer, drive, dir, fname, ext );




上一篇:如何修改一个编辑框的字体
下一篇:如何模拟按下"计算器"的"7"键?
[置顶] 如何给多维数组赋初值

 

1;