【MFC】怎么获取文件路径和目录

【MFC】如何获取文件路径和目录

 MFC应用

一些简单获取路径、子路径、文件目录和判断路径有效的方法

// GetSubPath 从路径名中得到子路径
LPCTSTR CDirTreeCtrl::GetSubPath(LPCTSTR strPath)
{
	static CString strTemp;
	int iPos;
	strTemp = strPath;
	if ( strTemp.Right(1) == ’\\’ )
	strTemp.SetAt( strTemp.GetLength() - 1, ’\0’ );
	iPos = strTemp.ReverseFind( ’\\’ );
	if ( iPos != -1 )
	strTemp = strTemp.Mid( iPos + 1);
	return (LPCTSTR)strTemp;
}
// FindSubDir 找到子目录
BOOL CDirTreeCtrl::FindSubDir( LPCTSTR strPath)
{
	CFileFind find;
	CString strTemp = strPath;
	BOOL bFind;
	if ( strTemp[strTemp.GetLength()-1] == ’\\’ )
	strTemp += "*.*";
	else
	strTemp += "\\*.*";
	bFind = find.FindFile( strTemp );
	while ( bFind )
	{

		bFind = find.FindNextFile();
		if ( find.IsDirectory() && !find.IsDots() )
		{
		return TRUE;
		}
		if(!find.IsDirectory()&&m_bFiles && !find.IsHidden() )
		return TRUE;
	}
	return FALSE;
}
///获取全路径
CString CDirTreeCtrl::GetFullPath(HTREEITEM hItem)
{
	CString strReturn;
	CString strTemp;
	HTREEITEM hParent = hItem;
	strReturn = "";
	while ( hParent )
	{
	strTemp = GetItemText( hParent );
	strTemp += "\\";
	strReturn = strTemp + strReturn;
	hParent = GetParentItem( hParent );
	}
	strReturn.TrimRight( ’\\’ );
	return strReturn;
}
// IsValidPath 判断路径是否有效
BOOL CDirTreeCtrl::IsValidPath(LPCTSTR strPath)
{
	HTREEITEM hChild;
	CString strItem;
	CString strTempPath = strPath;
	BOOL bFound = FALSE;
	CFileFind find;
	hChild = GetChildItem( TVI_ROOT );
	strTempPath.MakeUpper();
	strTempPath.TrimRight(’\\’);
	while ( hChild )
	{
	strItem = GetItemText( hChild );
	strItem.MakeUpper();
	if ( strItem == strTempPath.Mid( 0, strItem.GetLength() ) )
	{
	bFound = TRUE;
	break;
	}
	hChild = GetNextItem( hChild, TVGN_NEXT );
	}
	if ( !bFound )
	return FALSE;
	strTempPath += "\\nul";
	if ( find.FindFile( strTempPath ) )
	return TRUE;
	return FALSE;
}