Win32 Programming: Operation on Files
Posted on In ProgrammingHere, we show some example code on Win32. The code are operations on file on Win32 OSes. The code here uses some MFC classes.
Recursively show the files from a path:
void Show(const char *folderPath) { CFileFind finder; CString path(folderPath); path += "*.*"; BOOL bWorking = finder.FindFile(path); while (bWorking) { bWorking = finder.FindNextFile(); cout << finder.GetFilePath() << endl; } finder.Close(); }
Recursively copy a folder:
bool CopyFolder(const char *srcFolderPath, const char *dstFolderPath) { CFileFind srcFinder, dstFinder; CString src(srcFolderPath); CString dst(dstFolderPath); if (!CreateDirectory(dst.GetBuffer(), 0)) return false; CFileFind finder; BOOL bWorking = finder.FindFile(src + "*.*"); while (bWorking) { bWorking = finder.FindNextFile(); if (finder.IsDots()) continue; CString fileName = finder.GetFileName(); if (finder.IsDirectory()) { if (!CopyFolder((src + "" + fileName).GetBuffer(), dst + "" + fileName)) { finder.Close(); return false; } } else { if (!CopyFile(src + "" + fileName, dst + "" + fileName, 0)) { finder.Close(); return false; } } } finder.Close(); return true; }
Recursively delete a folder and the content in it:
bool DeleteFolder(const char *folderName) { CString path(folderName); CFileFind finder; BOOL bWorking = finder.FindFile(path + "*.*"); while (bWorking) { bWorking = finder.FindNextFile(); if (finder.IsDots()) continue; CString fileName = finder.GetFileName(); if (finder.IsDirectory()) { if (!DeleteFolder((path + "" + fileName).GetBuffer())) { finder.Close(); return false; } } else { if (!DeleteFile((path + "" + fileName).GetBuffer())) { finder.Close(); return false; } } } finder.Close(); return RemoveDirectory(folderName); }