软件架构师何志丹头像

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

                                                               

已知文件名,如何取文件所在目录?最简单的方法是从后向前找"//".但有时,文件名中没有"//",这时要先转化一下.具体代码如下:

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

计算几何为骨,排样优化为魂
作品一亲士套料工具箱文章配图https://qinshi.blog.csdn.net/article/details/167222655 作品二亲士CAD工具箱文章配图https://qinshi.blog.csdn.net//article/details/156510081 经典文章推荐:二维排样文章配图https://qinshi.blog.csdn.net/article/details/164169163零代码可视化工具文章配图https://blog.csdn.net/le5le_iot可视化、物联网、工业互联网与AI 大佬文章配图https://blog.csdn.net/Alsmile万物皆数学文章配图https://qinshi.blog.csdn.net/article/details/143057305 查阅鄙人的博文,请点击博文下载学院导航文章配图https://qinshi.blog.csdn.net/article/details/163717324
活到老,学到老。明朝中后期,大约50%的进士能当上堂官(副部及更高);能当上堂官的举人只有十余人。
子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/he_zhidan/article/details/1684767

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--