用到的API和数据结构:
WINDOWS数据结构:
WIN32_FIND_DATA
WINDOWS API:
FindFirstFile
FindNextFile
CompareFileTime
CopyFIle
DeleteFile
View Code
#include <windows.h> #include <iostream> #include <string> using namespace std; #define MAXN 10000 typedef struct _SRCFILE {WIN32_FIND_DATA fd;//我WIN32_FIND_DATA关于文件的全部属性信息的数据结构bool IsNew; }SRCFILE;SRCFILE srcFiles[MAXN], desFiles[MAXN];WIN32_FIND_DATA fd; int iSrcFiles; int iDesFiles;void get_source(string str) {bool bRet = true;iSrcFiles = 0;HANDLE hFile = FindFirstFile(str.c_str(),&fd);while( hFile != INVALID_HANDLE_VALUE && bRet ){if( fd.dwFileAttributes == FILE_ATTRIBUTE_ARCHIVE ){srcFiles[iSrcFiles].fd = fd;srcFiles[iSrcFiles].IsNew = false;iSrcFiles++;}bRet = FindNextFile(hFile, &fd);}}void get_destion(string str) {bool bRet = true;iDesFiles = 0;HANDLE hFile = FindFirstFile(str.c_str(),&fd);while( hFile != INVALID_HANDLE_VALUE && bRet ){if( fd.dwFileAttributes == FILE_ATTRIBUTE_ARCHIVE ){desFiles[iDesFiles].fd = fd;desFiles[iDesFiles].IsNew = false;iDesFiles++;}bRet = FindNextFile(hFile, &fd);} }void solve(string sp, string st) {int i ,j;// printf("iSrcFiles = %d iDesFiles = %d\n", iSrcFiles, iDesFiles);for(i = 0; i < iSrcFiles; i++){ int f = 0;for(j = 0; j < iDesFiles; j++){if( strcmp(srcFiles[i].fd.cFileName,desFiles[j].fd.cFileName) == 0 && CompareFileTime(&srcFiles[i].fd.ftLastWriteTime, &desFiles[j].fd.ftLastWriteTime) == 0 ){f = 1;break;}}if( !f )srcFiles[i].IsNew = true;elsedesFiles[i].IsNew = true;}for( i = 0; i < iSrcFiles; i++){if( srcFiles[i].IsNew ){string spath = sp + srcFiles[i].fd.cFileName;string dpath = st + srcFiles[i].fd.cFileName;printf("备份的是:%s\n", spath.c_str());CopyFile(spath.c_str(),dpath.c_str(),false);//备份也要指定路径+文件名 }}for(i = 0; i < iDesFiles; i++){if( desFiles[i].IsNew == false ){string dpath = st + desFiles[i].fd.cFileName; //cFileName只包含文件名,删除要指定路径printf("删除的是:%s\n",dpath.c_str());DeleteFile(dpath.c_str());}}}int main( ) {string str("E:\\桂林\\*.*"); //查询这个文件夹下的所有文件string st("D:\\桂林\\*.*"); get_source(str);get_destion(st);string sq("E:\\桂林\\");string sp("D:\\桂林\\");solve(sq,sp);return 0;}