歡迎使用CSDN-markdown編輯器

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=”“;
/*
CString path(%%1);
CString %%2=path.Mid(path.ReverseFind(‘\’)+1);
*/

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=”“;
/*
char appName[MAX_PATH];
GetModualFileName(NULL,appName,MAX_PATH);
*/

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.追加路徑
/*

include

include

include

include

*/
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);
}
}
}

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

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%7ccfile::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_%22+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

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(%%2+”//enc_%22+strfilename,cfile::moderead)){
//不能打開輸入文件
return;
}
if(!Out.Open(%%1,CFile::modeWrite | CFile::modeCreate)){
//不能打開輸出文件
return;
}
nFilesize=In.GetLength();
lpBuffer=new char[nFilesize];
if(lpBuffer==NULL){
//不能分配複製緩存
return;
}
CFileStatus rStatus;
In.GetStatus(%%2+”//enc_%22+strfilename,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

ifdef _DEBUG

pragma comment(lib,”zlibd.lib”)

else

pragma comment(lib,”zlib.lib”)

endif

include “zlib.h”

include “zconf.h”

*/
HANDLE hFile, hFileToWrite;
CString strFilePath;
m_ctrEdit.GetWindowText(strFilePath);

//打開要進行壓縮的文件
hFile = CreateFile(strFilePath, // file name
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // no security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template

if (hFile == INVALID_HANDLE_VALUE)
{
AfxMessageBox(“Could not open file to read”); // process error
return;
}

HANDLE hMapFile, hMapFileToWrite;

//創建一個文件映射
hMapFile = CreateFileMapping(hFile, // Current file handle.
NULL, // Default security.
PAGE_READONLY, // Read/write permission.
0, // Max. object size.
0, // Size of hFile.
“ZipTestMappingObjectForRead”); // Name of mapping object.

if (hMapFile == NULL)
{
AfxMessageBox(“Could not create file mapping object”);
return;
}

LPVOID lpMapAddress, lpMapAddressToWrite;

//創建一個文件映射的視圖用來作爲source
lpMapAddress = MapViewOfFile(hMapFile, // Handle to mapping object.
FILE_MAP_READ, // Read/write permission
0, // Max. object size.
0, // Size of hFile.
0); // Map entire file.

if (lpMapAddress == NULL)
{
AfxMessageBox(“Could not map view of file”);
return;
}
DWORD dwFileLength,dwFileLengthToWrite;
dwFileLength = GetFileSize(hFile, NULL);
m_dwSourceFileLength = dwFileLength;
//因爲壓縮函數的輸出緩衝必須比輸入大0.1% + 12 然後一個DWORD用來保存壓縮前的大小,
// 解壓縮的時候用,當然還可以保存更多的信息,這裏用不到
dwFileLengthToWrite = (double)dwFileLength*1.001 + 12 +sizeof(DWORD);
//以下是創建一個文件,用來保存壓縮後的文件
hFileToWrite = CreateFile(“demoFile.rar”, // demoFile.rar
GENERIC_WRITE|GENERIC_READ, // open for writing
0, // do not share

NULL, // no security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL , // normal file
NULL); // no attr. template

if (hFileToWrite == INVALID_HANDLE_VALUE)
{
AfxMessageBox(“Could not open file to write”); // process error
return;
}
hMapFileToWrite = CreateFileMapping(hFileToWrite, // Current file handle.
NULL, // Default security.
PAGE_READWRITE, // Read/write permission.
0, // Max. object size.
dwFileLengthToWrite, // Size of hFile.
“ZipTestMappingObjectForWrite”); // Name of mapping object.
if (hMapFileToWrite == NULL)
{
AfxMessageBox(“Could not create file mapping object for write”);
return;
}
lpMapAddressToWrite = MapViewOfFile(hMapFileToWrite, //Handle to mapping

object.FILE_MAP_WRITE, // Read/write permission
0, // Max. object size.
0, // Size of hFile.
0); // Map entire file.
if (lpMapAddressToWrite == NULL)
{
AfxMessageBox(“Could not map view of file”);
return;
}
//這裏是將壓縮前的大小保存在文件的第一個DWORD裏面
LPVOID pBuf = lpMapAddressToWrite;
((DWORD)pBuf) = dwFileLength;
pBuf = (DWORD*)pBuf + 1;
//這裏就是最重要的,zlib裏面提供的一個方法,將源緩存的數據壓縮至目的緩存
//原形如下:
//int compress (Bytef *dest, uLongf *destLen, const Bytef*source, uLong

sourceLen);
//參數destLen返回實際壓縮後的文件大小。
compress((Bytef*)pBuf,&dwFileLengthToWrite, (Bytef*)lpMapAddress, dwFileLength);
UnmapViewOfFile(lpMapAddress);
CloseHandle(hMapFile);
CloseHandle(hFile);
UnmapViewOfFile(lpMapAddressToWrite);
CloseHandle(hMapFileToWrite);
//這裏將文件大小重新設置一下
SetFilePointer(hFileToWrite,dwFileLengthToWrite + sizeof(DWORD)

,NULL,FILE_BEGIN);
SetEndOfFile(hFileToWrite);
CloseHandle(hFileToWrite);
40.ZIP解壓縮
//www.zlib.net
/*

ifdef _DEBUG

pragma comment(lib,”zlibd.lib”)

else

pragma comment(lib,”zlib.lib”)

endif

include “zlib.h”

include “zconf.h”

*/
HANDLE hFile, hFileToWrite;
CString strFilePath;
m_ctrEdit.GetWindowText(strFilePath);
//打開要進行解壓縮的文件
hFile = CreateFile(strFilePath, // file name
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // no security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE)
{
AfxMessageBox(“Could not open file to read”); // process error
return;
}
HANDLE hMapFile, hMapFileToWrite;
//創建一個文件映射
hMapFile = CreateFileMapping(hFile, // Current file handle.
NULL, // Default security.
PAGE_READONLY, // Read/write permission.
0, // Max. object size.
0, // Size of hFile.
“ZipTestMappingObjectForRead”); // Name of mapping object.
if (hMapFile == NULL)
{
AfxMessageBox(“Could not create file mapping object”);
return;
}
LPVOID lpMapAddress, lpMapAddressToWrite;
//創建一個文件映射的視圖用來作爲source
lpMapAddress = MapViewOfFile(hMapFile, // Handle to mapping
object.FILE_MAP_READ, // Read/write permission
0, // Max. object size.
0, // Size of hFile.
0); // Map entire file.
if (lpMapAddress == NULL)
{
AfxMessageBox(“Could not map view of file”);
return;
}
DWORD dwFileLength,dwFileLengthToWrite;
dwFileLength = GetFileSize(hFile, NULL) - sizeof(DWORD);
//因爲壓縮函數的輸出緩衝必須比輸入大0.1% + 12 然後一個DWORD用來保存壓縮前的大小,
// 解壓縮的時候用,當然還可以保存更多的信息,這裏用不到
// dwFileLengthToWrite = (double)dwFileLength*1.001 + 12 +sizeof(DWORD);
dwFileLengthToWrite = ((DWORD)lpMapAddress);

LPVOID pSourceBuf = lpMapAddress;
pSourceBuf = (DWORD*)pSourceBuf + 1;
//以下是創建一個文件,用來保存壓縮後的文件
hFileToWrite = CreateFile(“demoFile.pdf”, // create demo.gz
GENERIC_WRITE|GENERIC_READ, // open for writing
0, // do not share
NULL, // no security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL , // normal file
NULL); // no attr. template
if (hFileToWrite == INVALID_HANDLE_VALUE)
{
AfxMessageBox(“Could not open file to write”); //process error
return;
}
hMapFileToWrite = CreateFileMapping(hFileToWrite, // Currentfile handle.
NULL, // Default security.
PAGE_READWRITE, // Read/write permission.
0, // Max. object size.
dwFileLengthToWrite, // Size of hFile.
“ZipTestMappingObjectForWrite”); // Name of mapping object.
if (hMapFileToWrite == NULL)
{
AfxMessageBox(“Could not create file mapping object for write”);
return;
}
lpMapAddressToWrite = MapViewOfFile(hMapFileToWrite, //Handle to mapping object.
FILE_MAP_WRITE, // Read/write permission
0, // Max. object size.
0, // Size of hFile.
0); // Map entire file.
if (lpMapAddressToWrite == NULL)
{
AfxMessageBox(“Could not map view of file”);
return;
}
//這裏是將壓縮前的大小保存在文件的第一個DWORD裏面
LPVOID pBuf = lpMapAddressToWrite;
//這裏就是最重要的,zlib裏面提供的一個方法,將源緩存的數據壓縮至目的緩存
//原形如下:
//int compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);
//參數destLen返回實際壓縮後的文件大小。
uncompress((Bytef*)pBuf,&dwFileLengthToWrite, (Bytef*)pSourceBuf, dwFileLength);
UnmapViewOfFile(lpMapAddress);
CloseHandle(hMapFile);
CloseHandle(hFile);
UnmapViewOfFile(lpMapAddressToWrite);
CloseHandle(hMapFileToWrite);
//這裏將文件大小重新設置一下
SetFilePointer(hFileToWrite,dwFileLengthToWrite,NULL,FILE_BEGIN);
SetEndOfFile(hFileToWrite);
CloseHandle(hFileToWrite);

41.獲得應用程序完整路徑
char appName[MAX_PATH];
GetModuleFileName(NULL,appName,MAX_PATH);
CString %%1(appName);
42.ZIP壓縮文件夾
//www.zlib.net
/*

include

include

include

include

include

include

#if defined(MSDOS) || defined(OS2) || defined(WIN32) ||
defined(CYGWIN)

include

include

define SET_BINARY_MODE(file) setmode(fileno(file),

O_BINARY)
#else
# define SET_BINARY_MODE(file)
#endif

define CHUNK 16384

//#define USE_TAG
#ifdef USE_TAG
#define COMPRESS_FILE_TAG_HEAD “<<<”
#define COMPRESS_FILE_TAG_TAIL “>>>”
#define COMPRESS_FILE_TAG_END_LEN 3 // must be strlen
(COMPRESS_FILE_TAG_HEAD) = strlen(COMPRESS_FILE_TAG_TAIL)

else

define COMPRESS_FILE_TAG_HEAD “”

define COMPRESS_FILE_TAG_TAIL “”

define COMPRESS_FILE_TAG_END_LEN 0 // must be strlen

(COMPRESS_FILE_TAG_HEAD) = strlen(COMPRESS_FILE_TAG_TAIL)
#endif
*/
/////*// Compress from file source to file dest until

EOF on source.
def() returns Z_OK on success, Z_MEM_ERROR if memory could

not be
allocated for processing, Z_STREAM_ERROR if an invalid

compression
level is supplied, Z_VERSION_ERROR if the version of zlib.h

and the
version of the library linked do not match, or Z_ERRNO if

there is
an error reading or writing the files. */
static int def(FILE *source, FILE *dest, int level)
{
int ret, flush;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];

/////*// allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, level);
if (ret != Z_OK)
return ret;
/////*// compress until end of file */
do {
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;

/////*// run deflate() on input until output

buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = deflate(&strm, flush); /////*// no

bad return value */
assert(ret != Z_STREAM_ERROR); /////*//

state not clobbered */
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror

(dest)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
} while (strm.avail_out == 0);
assert(strm.avail_in == 0); /////*// all

input will be used */

/////*// done when last data in file processed

*/
} while (flush != Z_FINISH);
assert(ret == Z_STREAM_END); /////*// stream

will be complete */

/////*// clean up and return */
(void)deflateEnd(&strm);
return Z_OK;
}
/////*// Decompress from file source to file dest until

stream ends or EOF.
inf() returns Z_OK on success, Z_MEM_ERROR if memory could

not be
allocated for processing, Z_DATA_ERROR if the deflate data

is
invalid or incomplete, Z_VERSION_ERROR if the version of

zlib.h and
the version of the library linked do not match, or Z_ERRNO

if there
is an error reading or writing the files. */
static int inf(FILE *source, FILE *dest)
{
int ret;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];

/////*// allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm);
if (ret != Z_OK)
return ret;

/////*// decompress until deflate stream ends or end

of file */
do {
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
(void)inflateEnd(&strm);
return Z_ERRNO;
}
if (strm.avail_in == 0)
break;
strm.next_in = in;

/////*// run inflate() on input until output

buffer not full */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR); /////*//

state not clobbered */
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR; /////*// and

fall through */
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
return ret;
}
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror

(dest)) {
(void)inflateEnd(&strm);
return Z_ERRNO;
}
} while (strm.avail_out == 0);

/////*// done when inflate() says it’s done */
} while (ret != Z_STREAM_END);

/////*// clean up and return */
(void)inflateEnd(&strm);
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
/////*// report a zlib or i/o error */
static void zerr(int ret)
{
fputs(“zpipe: “, stderr);
switch (ret) {
case Z_ERRNO:
if (ferror(stdin))
fputs(“error reading stdin “, stderr);
if (ferror(stdout))
fputs(“error writing stdout “, stderr);
break;
case Z_STREAM_ERROR:
fputs(“invalid compression level “, stderr);
break;
case Z_DATA_ERROR:
fputs(“invalid or incomplete deflate data “, stderr);
break;
case Z_MEM_ERROR:
fputs(“out of memory “, stderr);
break;
case Z_VERSION_ERROR:
fputs(“zlib version mismatch! “, stderr);
}
}
// 以上就是zpipe.c的幾個主要函數:def()、inf()和zerr(),def()是壓縮函數,主要使用了zlib的deflate()接口;inf()是壓縮函數,主要

使用了zlib的inflate()接口;zerr()是錯誤打印函數。
static int write_zfile_file_header(const char *file,FILE *zfile)
{
int len;
len = strlen(file);
if (fwrite(COMPRESS_FILE_TAG_HEAD, 1,COMPRESS_FILE_TAG_END_LEN, zfile) != COMPRESS_FILE_TAG_END_LEN || ferror(zfile))
{
fprintf(stderr,”When writing file or dir header to zfile: write error. “);
return 1;
}
if (fwrite(file, 1, len, zfile) != len|| ferror(zfile))
{
fprintf(stderr,”When writing file or dir header to zfile: write error. “);
return 1;
}
if (fwrite(COMPRESS_FILE_TAG_TAIL, 1,COMPRESS_FILE_TAG_END_LEN, zfile) != COMPRESS_FILE_TAG_END_LEN || ferror(zfile))
{
fprintf(stderr,”When writing file or dir header to

zfile: write error. “);
return 1;
}
return 0;
}
/*// compress or decompress from stdin to stdout */
static int compress_dir(char *file_in,FILE *fd_out)
{
FILE *fd_in;
struct _finddata_t find_data;
char file[128];
long lf;
int ret;
write_zfile_file_header(file_in,fd_out);
sprintf(file,”%s%s”,file_in,”/*”);
if((lf = _findfirst(file,&find_data))==-1l) // LOOKOUT:not eleven, but one and lowercase ‘L’
{
fprintf(stdout,”file not found. “);
}
else
{
do
{
if(!strcmp(find_data.name,”.”) || !strcmp(find_data.name,”..”))
continue;
fprintf(stdout,”%s”,find_data.name);
sprintf(file,”%s%s%s”,file_in,”/”,find_data.name);
if(find_data.attrib & _A_SUBDIR)
{
fprintf(stdout,” —directory— “);
ret = compress_dir(file,fd_out);
}
else
{
write_zfile_file_header(file,fd_out);
if(access(file, 2) != 0) //W_OK=2
{
int attrib;
attrib = _chmod(file,0);
_chmod(file,1,attrib & ~_A_RDONLY);
fprintf(stderr,”When writing file: No privilege to write file %s. “,file);
return -1;
}
fd_in = fopen(file,”rb+”);
SET_BINARY_MODE(fd_in);
ret = def(fd_in, fd_out,Z_DEFAULT_COMPRESSION);
if (ret != Z_OK)
zerr(ret);
else
fprintf(stdout,” zip over “);
fclose(fd_in);
}
}while( _findnext(lf, &find_data ) == 0 );
}
return 0;
}
int main(int argc, char **argv)
{
struct _finddata_t find_data;
FILE *fd_in;
FILE *fd_out;
const char *file_dir;
char file_out[100];
int ret;
if (argc == 2)
{
file_dir = argv[1];
if(_findfirst(file_dir,&find_data)==-1l) //LOOKOUT: not eleven, but one and lowercase ‘L’
{
fprintf(stderr,”File or dir %s not found.”,file_dir);
return 1;
}
if(find_data.attrib & _A_SUBDIR)
{
sprintf(file_out,”%s%s”,file_dir,”.z”);
fd_out = fopen(file_out,”wb+”);
SET_BINARY_MODE(fd_out);
fprintf(stdout,”Dir %s being Compressed …”,file_dir);
ret = compress_dir(file_dir,fd_out);
fclose(fd_out);
}
else
{
fprintf(stdout,”File %s being Compressed …”,file_dir);
sprintf(file_out,”%s%s”,file_dir,”.z”);
fd_in = fopen(file_dir,”rb+”);
fd_out = fopen(file_out,”wb+”);
SET_BINARY_MODE(fd_in);
SET_BINARY_MODE(fd_out);
ret = def(fd_in, fd_out, Z_DEFAULT_COMPRESSION);
fclose(fd_in);
fclose(fd_out);
}
if (ret != 0)
{
fprintf(stderr,”Compress Error !!!!!!!!!!!!!! “);
zerr(ret);
}
else
fprintf(stdout,”Compress OK————— “);
}
else {
fprintf(stdout,”zod usage: zod [file]/[directory] “);
}
getch();
return 0;
}
43.遞歸刪除目錄下的文件
CString Directory(%%1);
CStringArray csa;
int count=0;
if(Directory.Right(1)!=”\”)
Directory+=”\”;
Directory+=”.“;
CFileFInd FFile;
csa.add(Directory);
while(count

include

// Create a SAX2 parser object.
SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
// Set the appropriate features on the parser.
// Enable namespaces, schema validation, and the checking
// of all Schema constraints.
// We refer to these as “common features” in following examples.
parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
parser->setFeature(XMLUni::fgXercesDynamic, false);
parser->setFeature(XMLUni::fgXercesSchema, true);
parser->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
// Set appropriate ContentHandler, ErrorHandler, and EntityResolver.
// These will be referred to as “common handlers” in subsequent examples.
// You will use a default handler provided by Xerces-C++ (no op action).
// Users should write their own handlers and install them.
DefaultHandler handler;
parser->setContentHandler(&handler);
// The object parser calls when it detects violations of the schema.
parser->setErrorHandler(&handler);
// The object parser calls to find the schema and
// resolve schema imports/includes.
parser->setEntityResolver(&handler);
// Parse the XML document.
// Document content sent to registered ContentHandler instance.
parser->parse(xmlFile);
// Delete the parser instance.
delete parser;
46.Grep
void BrowseFile(CString strFile)
{
CFileFind ff;
CString szDir = strFile;
if(szDir.Right(1) != “\”)
szDir += “\”;
szDir += “.“;
BOOL res = ff.FindFile(szDir);
while(res)
{
res = ff.FindNextFile();
if(ff.IsDirectory() && !ff.IsDots())//目錄是文件夾
{
//如果是一個子目錄,用遞歸繼續往深一層找
CString strPath = ff.GetFilePath(); //得到路徑,做爲遞歸調用的開始
CString strTitle = ff.GetFileTitle();//得到目錄名,做爲樹控的結點
BrowseFile(strPath);//遞歸調用
}
else if(!ff.IsDots())
{
//顯示當前訪問的文件
CString strPath;
strPath = ff.GetFilePath();
//AfxMessageBox(m_find_str);
findStrInFile(strPath);
//strTitle = ff.GetFileTitle();
}
}
ff.Close();//關閉
}

void findStrInFile(CString filePath)
{
FILE *fp;
char ch[256];
//char fpath[256];
// sprintf(fpath,”%s”,filePath);
//CString temp;
//AfxMessageBox(fpath);
fp = fopen(filePath,”r”);
while(!feof(fp))
{
memset(ch, 0, sizeof(ch));
//AfxMessageBox(“aaaa”);
fgets((char *)ch, sizeof(ch)-1, fp);
if(strstr(ch,m_find_str))
{
m_find_res+=filePath+”\r\n”;
fclose(fp);
//UpdateData(FALSE);
CString strTemp;
strTemp.Format(“%d”,resNum);
m_list_res.InsertItem(resNum,strTemp);
//strTemp.Empty();
//strTemp.Format(“%d”,100);
//char buf[128];
//sprintf(buf,”%d”,100);//AfxMessageBox(“aaaaa”);
m_list_res.SetItemText(resNum,1,strTemp);
// memset(buf,0,100);
// sprintf(buf,”%s”,filePath);
//AfxMessageBox(“aaaaa”);
m_list_res.SetItemText(resNum,2,filePath);
resNum++;
return;
}
//AfxMessageBox(“aaaa”);
//temp.Format(ch);
//AfxMessageBox(temp);
/*if(temp.Find(m_find_str))
{
m_find_res+=filePath+”\r\n”;
fclose(fp);
return;
}*/
}
fclose(fp);
}

void OnOK_ToFind()
{
UpdateData(TRUE);
m_find_path=Buffer;
//AfxMessageBox(m_find_path);
BrowseFile(m_find_path);
UpdateData(FALSE);
}
void OnButtonFindPath()
{
//選擇路徑
BROWSEINFO bi;
memset(Buffer,0,MAX_PATH);
//初始化入口參數bi開始
bi.hwndOwner = NULL;
bi.pidlRoot = NULL;
bi.pszDisplayName = Buffer;//此參數如爲NULL則不能顯示對話框
bi.lpszTitle = “選擇路徑”;
bi.ulFlags = 0;
bi.lpfn = NULL;
// bi.iImage=IDR_MAINFRAME;
//初始化入口參數bi結束
LPITEMIDLIST pIDList = SHBrowseForFolder(&bi);//調用顯示選擇對話框
if(pIDList)
{
SHGetPathFromIDList(pIDList, Buffer);
//取得文件夾路徑到Buffer裏
}
LPMALLOC lpMalloc;
if(FAILED(SHGetMalloc(&lpMalloc))) return;
//釋放內存
lpMalloc->Free(pIDList);
lpMalloc->Release();

}
void OnButtonClear()
{
m_find_path.Empty();
m_find_str.Empty();
m_find_res.Empty();
UpdateData(FALSE);
}

47.直接創建多級目錄
/*
typedef BOOL (__stdcall funMakeSure(LPCSTR DirPath));
funMakeSure *MakeSureDirectoryPathExists;
HMODULE hMod=LoadLibrary(“dbghelp.dll”);
MakeSureDirectoryPathExists(*funMakeSure)GetProcAddress(hMod,”MakeSureDirectoryPathExists”);
*/
MakeSureDirectoryPathExists(%%1);

48.批量重命名
CString strPath,strFilter,srcTitle,src,srcFile,dstFile,dstFileTitle;
int i=1,iFileNum=1;
CFile myFile,newFile;
//獲取將要批量處理的文件夾及文件格式
GetDlgItemText(IDC_SRC,strPath);
GetDlgItemText(IDC_EXT,strFilter);
//判斷文件夾是否爲空
if(strPath.IsEmpty())
{
MessageBox(“請先選擇要重命名文件所在文件夾!”,”警告!”);
return;
}
//在該文件夾內創建目錄文件
src=strPath+”*.”+strFilter;

CString list=strPath+”目錄.txt”;

if(myFile.Open(list,CFile::modeCreate|CFile::modeReadWrite,0) ==0) return;

CFileFind tempFind;
BOOL isFound=(BOOL)tempFind.FindFile(src);
//確定該文件夾內要處理的有多少個文件
while(isFound)
{
isFound=(BOOL)tempFind.FindNextFile();
if(tempFind.IsDirectory())
{
continue;
}
iFileNum++;
}
//進行文件名的轉換,以文件數定轉換後的文件名,如果有9個文件,則以1-9的形式命名,如果是更多,如有99個文件,則爲01-99的形式
isFound=(BOOL)tempFind.FindFile(src);

while(isFound && i

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章