1. 程式人生 > >【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;
}