C++ :常用文件、文件夹操作汇总
生活随笔
收集整理的這篇文章主要介紹了
C++ :常用文件、文件夹操作汇总
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文件、文件夾操作
- 1.創建文件夾
- 2.創建文件
- 3.刪除文件
- 4.刪除文件夾
- 5.刪除一個目錄下所有的文件夾
- 6.清空文件夾
- 7.讀取文件
- 8.寫入文件
- 9.寫入隨機文件
- 10.讀取文件屬性
- 11.寫入屬性
- 12.枚舉一個文件夾中的所有文件夾
- 13.復制文件夾
- 14.復制一個文件夾下所有的文件夾到另一個文件夾下
- 15.移動文件夾
- 16.移動一個文件夾下所有的文件夾到另一個目錄下
- 17.以一個文件夾的框架在另一個目錄創建文件夾和空文件
- 18.復制文件
- 19.復制一個文件夾下所有的文件到另一個目錄
- 20.提取擴展名
- 21.提取文件名
- 22.提取文件路徑
- 23.替換擴展名
- 24.追加路徑
- 25.移動文件
- 27.指定目錄下搜索文件
- 29.文件分割
- 30.文件合并
- 31.文件簡單加密
- 32 文件名修改
1.創建文件夾
CreateDirectory(%%1,NULL);2.創建文件
CFile file; file.Open(%%1,CFile::modeCreate|CFile::modeWrite);3.刪除文件
DeleteFile(%%1);4.刪除文件夾
RemoveDirectory(%%1);
5.刪除一個目錄下所有的文件夾
CFileFind finder; BOOL bWorking = finder.FindFile(%%1+"\\*.*"); while (bWorking) { bWorking = finder.FindNextFile(); if (finder.IsDirectory()) { dir.Delete(finder.GetFilePath()); } }6.清空文件夾
RemoveDirectory(%%1); CreateDirectory(%%1,NULL)7.讀取文件
char sRead[1024]; CFile mFile(_T(%%1),CFile::modeRead); while (sRead!=null) { mFile.Read(sRead,1024); CString %%2=CString(sRead); %%3 }8.寫入文件
CFile mFile(_T(%%1), CFile::modeWrite|CFile::modeCreate); mFile.Write(%%2,sizeof(%%2)); mFile.Flush(); mFile.Close();9.寫入隨機文件
char szTempPath[_MAX_PATH],szTempfile[_MAX_PATH]; GetTempPath(_MAX_PATH, szTempPath); GetTempFileName(szTempPath,_T ("my_"),0,szTempfile); CFile m_tempFile(szTempfile,CFile:: modeCreate|CFile:: modeWrite); char m_char='a'; m_tempFile.Write(&m_char,2); m_tempFile.Close(); //循環寫入多個值 strTempA; int i; int nCount=6; //共有6個文件名需要保存 for (i=0;i{strTemp.Format("%d",i); strTempA=文件名; //文件名可以從數組,列表框等處取得. ::WritePrivateProfileString("UseFileName","FileName"+strTemp,strTempA, c:\\usefile\\usefile.ini); } strTemp.Format("%d",nCount); ::WritePrivateProfileString("FileCount","Count",strTemp,"c:\\usefile\\usefile.ini"); //將文件總數寫入,以便讀出. //讀出 nCount=::GetPrivateProfileInt("FileCount","Count",0,"c:\\usefile\\usefile.ini"); for(i=0;i{strTemp.Format("%d",i); strTemp="FileName"+strTemp; ::GetPrivateProfileString("CurrentIni",strTemp,"default.fil", strTempA.GetBuffer(MAX_PATH),MAX_PATH,"c:\\usefile\\usefile.ini"); //使用strTempA中的內容. }10.讀取文件屬性
dwAttrs = GetFileAttributes(%%1); if (dwAttrs & FILE_ATTRIBUTE_READONLY) { %%2 } if (NORMAL & FILE_ATTRIBUTE_READONLY){ %%3 }11.寫入屬性
SetFileAttributes(szNewPath,dwAttrs | FILE_ATTRIBUTE_READONLY);12.枚舉一個文件夾中的所有文件夾
CFileFind finder; BOOL bWorking = finder.FindFile(%%1+"\\*.*"); while (bWorking) { bWorking = finder.FindNextFile(); if(finder.IsDirectory()){ CString %%1=finder.GetFilePath(); %%2 } }13.復制文件夾
WIN32_FIND_DATA FileData; HANDLE hSearch; DWORD dwAttrs; char szDirPath[] = %%2; char szNewPath[MAX_PATH]; char szHome[MAX_PATH]; BOOL fFinished = FALSE; if (!CreateDirectory(szDirPath, NULL)) { //不能創建新的目錄 return; } hSearch = FindFirstFile(%%1+"\\*.*", &FileData); if (hSearch == INVALID_HANDLE_VALUE) { return; } while (!fFinished) { lstrcpy(szNewPath, szDirPath); lstrcat(szNewPath, FileData.cFileName); if (CopyFile(FileData.cFileName, szNewPath, FALSE)) { dwAttrs = GetFileAttributes(FileData.cFileName); if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) { SetFileAttributes(szNewPath, dwAttrs | FILE_ATTRIBUTE_READONLY); } } else { //不能復制文件 return; } if (!FindNextFile(hSearch, &FileData)) { if (GetLastError() == ERROR_NO_MORE_FILES) { //遍歷文件夾完成 fFinished = TRUE; } else { //找不到下一個文件 return; } } } FindClose(hSearch);14.復制一個文件夾下所有的文件夾到另一個文件夾下
WIN32_FIND_DATA FileData; HANDLE hSearch; DWORD dwAttrs; char szDirPath[] = %%2; char szNewPath[MAX_PATH]; char szHome[MAX_PATH]; BOOL fFinished = FALSE; if (!CreateDirectory(szDirPath,NULL)) { //不能創建新的目錄 return; } BOOL bWorking = finder.FindFile(%%1+"\\*.*"); while (bWorking) { bWorking = finder.FindNextFile(); if(finder.IsDirectory()){ hSearch = FindFirstFile(finder.GetFilePath()+"\\*.*", &FileData); if (hSearch == INVALID_HANDLE_VALUE) { return; } while (!fFinished) { lstrcpy(szNewPath, szDirPath); lstrcat(szNewPath, FileData.cFileName); if (CopyFile(FileData.cFileName, szNewPath, FALSE)) { dwAttrs = GetFileAttributes(FileData.cFileName); if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) { SetFileAttributes(szNewPath, dwAttrs | FILE_ATTRIBUTE_READONLY); } } else { //不能復制文件 return; } if (!FindNextFile(hSearch, &FileData)) { if (GetLastError() == ERROR_NO_MORE_FILES) { //遍歷文件夾完成 fFinished = TRUE; } else { //找不到下一個文件 return; } } } FindClose(hSearch); } }15.移動文件夾
WIN32_FIND_DATA FileData; HANDLE hSearch; DWORD dwAttrs; char szDirPath[] = %%2; char szNewPath[MAX_PATH]; char szHome[MAX_PATH]; BOOL fFinished = FALSE; if (!CreateDirectory(szDirPath, NULL)) { //不能創建新的目錄 return; } hSearch = FindFirstFile(%%1+"\\*.*", &FileData); if (hSearch == INVALID_HANDLE_VALUE) { return; } while (!fFinished) { lstrcpy(szNewPath, szDirPath); lstrcat(szNewPath, FileData.cFileName); if (CopyFile(FileData.cFileName, szNewPath, FALSE)) { dwAttrs = GetFileAttributes(FileData.cFileName); if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) { SetFileAttributes(szNewPath, dwAttrs | FILE_ATTRIBUTE_READONLY); } } else { //不能復制文件 return; } if (!FindNextFile(hSearch, &FileData)) { if (GetLastError() == ERROR_NO_MORE_FILES) { //遍歷文件夾完成 fFinished = TRUE; } else { //找不到下一個文件 return; } } } FindClose(hSearch); RemoveDirectory(%%1);16.移動一個文件夾下所有的文件夾到另一個目錄下
WIN32_FIND_DATA FileData; HANDLE hSearch; DWORD dwAttrs; char szDirPath[] = %%2; char szNewPath[MAX_PATH]; char szHome[MAX_PATH]; BOOL fFinished = FALSE; if (!CreateDirectory(szDirPath,NULL)) { //不能創建新的目錄 return; } BOOL bWorking = finder.FindFile(%%1+"\\*.*"); while (bWorking) { bWorking = finder.FindNextFile(); if(finder.IsDirectory()){ hSearch = FindFirstFile(finder.GetFilePath()+"\\*.*", &FileData); if (hSearch == INVALID_HANDLE_VALUE) { return; } while (!fFinished) { lstrcpy(szNewPath, szDirPath); lstrcat(szNewPath, FileData.cFileName); if (CopyFile(FileData.cFileName, szNewPath, FALSE)) { dwAttrs = GetFileAttributes(FileData.cFileName); if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) { SetFileAttributes(szNewPath, dwAttrs | FILE_ATTRIBUTE_READONLY); } } else { //不能復制文件 return; } if (!FindNextFile(hSearch, &FileData)) { if (GetLastError() == ERROR_NO_MORE_FILES) { //遍歷文件夾完成 fFinished = TRUE; } else { //找不到下一個文件 return; } } } FindClose(hSearch); RemoveDirectory(finder.GetFilePath().GetBuffer(0)); } }17.以一個文件夾的框架在另一個目錄創建文件夾和空文件
WIN32_FIND_DATA FileData; HANDLE hSearch; DWORD dwAttrs; char szDirPath[] = %%2; char szNewPath[MAX_PATH]; char szHome[MAX_PATH]; BOOL fFinished = FALSE; if (!CreateDirectory(szDirPath, NULL)) { //不能創建新的目錄 return; } hSearch = FindFirstFile(%%1+"\\*.*", &FileData); if (hSearch == INVALID_HANDLE_VALUE) { return; } while (!fFinished) { lstrcpy(szNewPath, szDirPath); lstrcat(szNewPath, FileData.cFileName); HANDLE hFile=CreateFileHandle hFile=CreateFile(szNewPath,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN,NULL); if(!hFile) { //不能創建文件 return; } if (!FindNextFile(hSearch, &FileData)) { if (GetLastError() == ERROR_NO_MORE_FILES) { //遍歷文件夾完成 fFinished = TRUE; } else { //找不到下一個文件 return; } } } FindClose(hSearch);18.復制文件
CopyFile(%%1,%%2,true)19.復制一個文件夾下所有的文件到另一個目錄
//#include using std::string; char sep='/'; #ifdef _WIN32 sep='\\'; #endif CFileFind finder; BOOL bWorking = finder.FindFile(%%1+"\\*.*"); while (bWorking) { bWorking = finder.FindNextFile(); if(!finder.IsDirectory() || finder.IsDots()){ string s(finder.GetFileName()); CString sourcefile(%%1); if(s.rfind(sep,s.length())!=string::npos) { sourcefile=sourcefile+"//"+s.substr(i+1,s.length()-i); CString targetfile(s.substr(i+1,s.length()-i)); targetfile=%%2+"//"+targetfile/; CopyFile(sourcefile.GetBuffer(0),targetfile.GetBuffer(0),true); } } }20.提取擴展名
//#include using std::string; string s(%%1); size_t i=s.rfind('.',s.length()); if(i!=string::npos) CString %%2(s.substr(i+1,s.length()-i)); else CString %%2="";21.提取文件名
//#include using std::string; string s(%%1); char sep='/'; #ifdef _WIN32 sep='\\'; #endif size_t i=s.rfind(sep,s.length()); if(i!=string::npos) CString %%2(s.substr(i+1,s.length()-i)); else CString %%2="";22.提取文件路徑
//#include using std::string; string s(%%1); char sep='/'; #ifdef _WIN32 sep='\\'; #endif size_t i=s.rfind(sep,s.length()); if(i!=string::npos) CString %%2(s.substr(0,i)); else CString %%2="";23.替換擴展名
//#include using std::string; string s(%%1); string newExt(%%2); string::size_type i=s.rfind('.',s.length()); if(i!=string::npos) s.replace(i+1,newExt.length(),newExt); CString %%3(s);24.追加路徑
using namespace std; using namespace boost::filesystem; try { path p1=complete(path(%%2,native), path(%%1,native)); path p2=system_complete(path(%%2,native)); CString %%3(p3); } catch(exception& e){ //e.what(); }25.移動文件
MoveFile(%%1,%%2);26.移動一個文件夾下所有文件到另一個目錄 //#include using std::string; char sep='/'; #ifdef _WIN32 sep='\\'; #endif CFileFind finder; BOOL bWorking = finder.FindFile(%%1+"\\*.*"); while (bWorking) { bWorking = finder.FindNextFile(); if(!finder.IsDirectory() || finder.IsDots()){ string s(finder.GetFileName()); CString sourcefile(%%1); if(s.rfind(sep,s.length())!=string::npos) { sourcefile=sourcefile+"//"+s.substr(i+1,s.length()-i); CString targetfile(s.substr(i+1,s.length()-i)); targetfile=%%2+"//"+targetfile/; MoveFile(sourcefile.GetBuffer(0),targetfile.GetBuffer(0),true); } } }實踐:
#include <iostream> if (m_nVisionDetectMode_cpp == Vision_Detect_MODE_AI) {//判斷文件個數 >1 存儲文件為NG CString NG_temp; NG_temp.Format(_T("D:\\DsTec\\AI\\Brand_%d\\device%d\\NG\\"), m_commbox_brand_index, nCurCameraIndex); if (NG_temp.Right(1) != L"\\") NG_temp += L"\\"; CString moveFile = NG_temp; NG_temp = NG_temp + L"*.*";CString Ai_NG_FILE; Ai_NG_FILE.Format(_T("D:\\DsTec\\AI\\NG_T\\")); if (Ai_NG_FILE.Right(1) != L"\\") Ai_NG_FILE += L"\\";CFileFind finder; BOOL bWorking = finder.FindFile(NG_temp); while (bWorking) {bWorking = finder.FindNextFile();CString filename = finder.GetFileName();MessageBox(filename);if (filename.Right(3) == "bmp" ){if (filename.GetLength() > 2) //有NG圖存在 觸發下位機信號{Ai_NG_FILE.Append(filename);moveFile.Append(filename);MessageBox(TEXT("有文件存在"));GPIOTEST.set_level(1, DefaultBitmask, LowLevel);MoveFile( moveFile,Ai_NG_FILE);}else{// MessageBox(TEXT("MO 有文件存在"));GPIOTEST.set_level(1, DefaultBitmask, HighLevel);}} } }ps:如果想修改文件名,只需要把目的路徑的文件名換成自己想更改的格式就行
27.指定目錄下搜索文件
CString strFileTitle; CFileFind finder; BOOL bWorking = finder.FindFile ("C:\\windows\\sysbkup\\*.cab"); while(bWorking) { bWorking=finder.FindNextFile(); strFileTitle=finder.GetFileTitle(); }28.打開對話框
CFileDialog mFileDlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_ALLOWMULTISELECT,"All Files (*.*)|*.*||",AfxGetMainWnd()); CString str(" ",10000); mFileDlg.m_ofn.lpstrFile=str.GetBuffer(10000); str.ReleaseBuffer(); POSITION mPos=mFileDlg.GetStartPosition(); CString pathName(" ",128); CFileStatus status; while(mPos!=NULL) { pathName=mFileDlg.GetNextPathName(mPos); CFile::GetStatus( pathName, status ); }29.文件分割
CFile m_File; CString m_Filename,m_FileTitle,m_FilePath; m_FileName=%%1; char pBuf[4096]; if(m_File.Open(m_FileName,CFile::modeRead | CFile::shareDenyWrite)) { m_FileName=m_File.GetPathName(); m_FileTitle=m_File.GetFileTitle(); DWORD FileLength=m_File.GetLength(); DWORD PartLength=FileLength/2+FileLength%2; int nCount=1; CString strName; CFile wrFile; DWORD ReadBytes; while(true) { ReadBytes=m_File.Read(pBuf,PartLength); strName.Format("%s%d",m_FIleTitle,nCount); wrFile.Open(strName,CFile::modeWrite | CFile::modeCreate); wrFile.Write(pBuf,ReadBytes); wrFile.Close(); if(ReadBytes break; nCount++; } m_File.Close(); } else AfxMessageBox("不能打開文件");30.文件合并
//#include using std::string; string s(%%1); char sep='/'; #ifdef _WIN32 sep='\\'; #endif size_t sz=s.rfind(sep,s.length()); if(sz!=string::npos) { CFile Out; CString strFilename(s.substr(i+1,s.length()-i)); if(Out.Open(%%2+"//"+strfilename,cfile::modewrite|cfile::modecreate)){ for(int i=1;i<=2;i++) { String Filename=%%%2+"//"+strfilename+atoi(i); CFile In; if(In.Open(Filename,CFile::modeRead)){ char cbBuffer[4096]; int nFilesize=In.GetLength(); while(nFilesize>0){ int nSize=sizeof(cbBuffer); if(nSize>nFilesize) nSize=nFilesize; try{ In.Read(cbBuffer,nSize); } catch(CFileException *e){ char *lpMsgBuf; if(FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,e->m_lOsError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf,0,NULL)>0){ AfxMessageBox(lpMsgBuf); LocalFree(lpMsgBuf); } e->Delete(); return; } try{ Out.Write(cbBuffer,nSize); } catch(CFileException *e){ char *lpMsgBuf; if(FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,e->m_lOsError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf,0,NULL)>0){ AfxMessageBox(lpMsgBuf); LocalFree(lpMsgBuf); } e->Delete(); return; } nFilesize=nSize; } } else AfxMessageBox("不能打開"+Filename); } } else AfxMessageBox("不能創建輸出文件"); }31.文件簡單加密
//#include using std::string; string s(%%1); char sep='/'; #ifdef _WIN32 sep='\\'; #endif size_t sz=s.rfind(sep,s.length()); if(sz!=string::npos) { CFile Out,In; int nFIlesize; char *lpMsgBuf; CString strFilename(s.substr(i+1,s.length()-i)); if(!in.Open(%%1,CFile::modeRead)){ //不能打開輸入文件 return; } if(!Out.Open(%%2+"//enc_"+strfilename,cfile::modewrite/ | CFile::modeCreate)){ //不能打開輸出文件 return; } nFilesize=In.GetLength(); lpBuffer=new char[nFilesize]; if(lpBuffer==NULL){ //不能分配復制緩存 return; } CFileStatus rStatus; In.GetStatus(%%1,rStatus); try{ In.Read(cbBuffer,nFilesize); } catch(CFileException *e){ char *lpMsgBuf; if(FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,e->m_lOsError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf,0,NULL)>0){ AfxMessageBox(lpMsgBuf); LocalFree(lpMsgBuf); } e->Delete(); return; } for(int i=0;i { int ibt=lpBuffer[i]; ibt+=100; ibt%=256; bpBuffer[i]=(char)ibt; } try{ Out.Write(cbBuffer,nFilesize); } catch(CFileException *e){ char *lpMsgBuf; if(FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,e->m_lOsError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf,0,NULL)>0){ AfxMessageBox(lpMsgBuf); LocalFree(lpMsgBuf); } e->Delete(); return; } Out.Close(); //In.Close(); CFile::SetStatus(%%2+"//enc_"+strfilename,rstatus); delete[] lpBuffer; }http://blog.chinaunix.net/uid-21768364-id-3244467.html
32 文件名修改
使用函數:rename
eg:
總結
以上是生活随笔為你收集整理的C++ :常用文件、文件夹操作汇总的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MFC:ListControl数据修改
- 下一篇: 吴恩达机器学习笔记:(一)机器学习方法简