在开发编译工具中,需要用到文件的相关操作,于是就封装了相关的函数实现:
//判断文件是否存在 BOOL FileIsExist(CString strFileName) { CFileFind finder; BOOL bWorking = finder.FindFile(strFileName); while(bWorking) { return TRUE; } return FALSE; } //获取ini文件信息 CString GetIniString(CString strAppName, CString strKeyName, CString strDefault, CString strFileName) { CString strRet; const int nMaxLength = 1024; GetPrivateProfileString(strAppName, strKeyName, strDefault,strRet.GetBuffer(nMaxLength), nMaxLength,strFileName); strRet.ReleaseBuffer(); return strRet; } // 得到文件的后缀名 CString GetFileExtension(CString fileName) { CString strFileNameExt = TEXT(""); int nPosExt = fileName.ReverseFind(TEXT('.')); strFileNameExt = fileName.Right(fileName.GetLength() - nPosExt - 1); return strFileNameExt; } //获取运行路径 CString GetRunPath() { TCHAR cbFilename[MAX_PATH + 1]={' '}; GetModuleFileName(NULL, cbFilename, MAX_PATH); CString strPath=cbFilename; strPath=strPath.Left(strPath.ReverseFind('\')); return strPath; } // 根据一个路径创建目录 void CreatePath(CString strPath) { CString dirName; CString strSub; CString strDrive; int nPos = 0; nPos = strPath.Find(TEXT(":")); dirName = strPath.Right(strPath.GetLength() - nPos -1); strDrive = strPath.Left(nPos + 1); int ia = 1; while (1) { AfxExtractSubString(strSub, dirName, ia, TEXT('\')); if (TEXT("") == strSub) { break; } ia++; strDrive += TEXT("\") + strSub; if (!PathFileExists(strDrive)) { CreateDirectory(strDrive, NULL); } } } // 删除一个目录下的所有文件 bool DeleteDirFiles(CString strDir) { // CreateDirectory(strDir, NULL); CreatePath(strDir); CFileFind finder; CString strFindDir; strFindDir.Format(TEXT("%s\*.*"), strDir); // MessageBox(strFindDir); BOOL bWorking = finder.FindFile(strFindDir); while(bWorking) { bWorking = finder.FindNextFile(); if (!finder.IsDirectory()) { DeleteFile(finder.GetFilePath()); } } finder.Close(); return false; } //根据路径获取文件名 CString GetFileNameFromPath(CString strPath) { CString strDirName = TEXT(""); int nPos = strPath.ReverseFind(TEXT('\')); if (-1 != nPos) { strDirName = strPath.Right(strPath.GetLength() - nPos -1); } return strDirName; }