MFC中我們往往需要遍歷某個路徑下的某個相關類型的文件,這就需要獲取目錄,我們一般使用的 BROWSEINFO 獲取路徑信息默認都是從根目錄開始展開,而CFileDialog獲取的一般都是文件路徑,也想過用CFileDialog獲取文件路徑,再剔除文件來獲取目錄,但始終不是所想要的那種效果。
下面通過BROWSEINFO獲取路徑,並且通過創建一個文件來保存每次打開的目錄從而達到記憶路徑功能。
1.設置一個全局變量來保存路徑,這個是為了保證程序執行后的路徑記憶:
static TCHAR g_szLastSelDir[MAX_PATH];
2.設置一個flag,程序執行以后就不用再從文件中來讀取路徑了,從上面的全局變量中讀取路徑。
static bool START_FLAG
3.獲取路徑程序如下
char buf[255]; //用來保存得到的路徑 //程序開始時直接從文件中讀取 if(START_FLAG == false) { CString LastPath = LastPahtGet(); _tcscpy(g_szLastSelDir, LastPath); } //程序開始 設置flag START_FLAG = true; BROWSEINFO bi; LPITEMIDLIST lp; CString BufferStr = _T(""); CString ShowBuffer = _T(""); ShowBuffer.LoadString(IDS_PRC_INPUT); ZeroMemory(buf, sizeof(buf)); bi.hwndOwner = m_hWnd; bi.pidlRoot = NULL; bi.pszDisplayName = buf; bi.lpszTitle = ShowBuffer; bi.ulFlags = BIF_RETURNONLYFSDIRS; bi.lpfn = BrowseCallbackProc;//設置回調函數,實現記憶路徑 bi.lParam = 0; bi.iImage = 0; lp = SHBrowseForFolder(&bi); PRC_IN_FLAG = false; if(lp!=NULL) { SHGetPathFromIDList(lp,buf); if(START_FLAG == true) { _tcscpy(g_szLastSelDir, buf);//程序執行后,獲取路徑 } PrcFileIntPath = CString(buf); LastPathSet(PrcFileIntPath);//每次打開目錄,保存目錄到文件 }
4.再把獲取路徑和寫路徑的程序也貼出來吧
獲取寫路徑到文件中 void LastPathSet(CString LastPath) { CStdioFile m_ReadMe; CString LineGetString = _T(""); CString ReadMeInf[1000]; bool PathFlag = false; int i = 0; int j = 0; //ReadMePath自己定義一個文件路徑 if( m_ReadMe.Open( ReadMePath, CFile::modeWrite|CFile:: modeCreate) ==0) { return; } else { m_ReadMe.WriteString(CString("LASTPATH:") + LastPath + CString("\\")); m_ReadMe.Close(); } }
從文件中獲取路徑 CString LastPahtGet(void) { CStdioFile m_ReadMe; int i; CString LineGetString = _T(""); if( m_ReadMe.Open( ReadMePath, CFile::modeRead|CFile::typeBinary) ==0) { return NULL; } else { m_ReadMe.ReadString(LineGetString); if(LineGetString.Find(CString("LASTPATH:"))!=-1) { LastPath = LineGetString.Mid(9,LineGetString.GetLength()-10); } m_ReadMe.Close(); if(PathFileExists(LastPath))//判斷該路徑是否存在 { return LastPath; } else { return CString(""); } } return CString(""); }
路徑文件中的字段
LASTPATH:C:\Documents and Settings\cnkangjb\デスクトップ\prc\