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());
}
}
请高手指点~
>> 本文固定链接: http://www.vcgood.com/archives/3141
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.写入文件
mFile.Close();
CFile mFile(_T(%%1), CFile::modeWrite|CFile::modeCreate);
mFile.Write(%%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;
file://共有6个文件名需要保存
for(i=0;i {strTemp.Format(“%d”,i);
strTempA=文件名;
file://文件名可以从数组,列表框等处取得.
::WritePrivateProfileString(“UseFileName”,”FileName”+strTemp,strTempA,
c:\\usefile\\usefile.ini);
}
strTemp.Format(“%d”,nCount);
::WritePrivateProfileString(“FileCount”,”Count”,strTemp,”c:\\usefile\\usefile.ini”);
file://将文件总数写入,以便读出.
//读出
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”);
file://使用strTempA中的内容.
}
10.读取文件属性
dwAttrs = GetFileAttributes(%%1);
if (dwAttrs & FILE_ATTRIBUTE_READONLY)
{
}
if (NORMAL & FILE_ATTRIBUTE_READONLY)
{
}
vcgood
http://www.vcgood.com
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);
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;
}
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));
}
}
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;
}
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);
17.复制文件
CopyFile(%%1,%%2,true)
18.复制一个文件夹下所有的文件到另一个目录
//#include <string>
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);
}
}
}
19.提取扩展名
//#include <string>
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=”";
20.提取文件名
//#include <string>
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=”";
21.提取文件路径
//#include <string>
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=”";
22.替换扩展名
//#include <string>
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);
23.追加路径
//#include <string>
//#include <cstdlib>
//#include <boost/filesystem/operations.hpp>
//#include <boost/filesystem/fstream.hpp>
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();
}
24.移动文件
MoveFile(%%1,%%2);
25.移动一个文件夹下所有文件到另一个目录
//#include <string>
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);
}
}
}
26.指定目录下搜索文件
CString strFileTitle;
CFileFind finder;
BOOL bWorking = finder.FindFile (“C:\\windows\\sysbkup\\*.cab”);
while(bWorking)
{
bWorking=finder.FindNextFile();
strFileTitle=finder.GetFileTitle();
}
27.打开对话框
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 );
}
28.文件分割
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<PartLength)
break;
nCount++;
}
m_File.Close();
}
else
AfxMessageBox(“不能打开文件”);
29.文件合并
//#include <string>
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(“不能创建输出文件”);
}
30.文件简单加密
//#include <string>
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<nFilesize;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;
}
31.文件简单解密
//#include <string>
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(%%2+”\\enc_”+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_”+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<nFilesize;i++)
{
int ibt=lpBuffer[i];
ibt-=100;ibt+=256;
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(%%1,rStatus);
delete[] lpBuffer;
}
32.读取ini文件属性
CString UGetProfileString(CString lpszSection,CString lpszEntry,CString def_str )
{
CStdioFile inifile(“Setup.ini”,CFile::modeRead);
path = inifile.GetFilePath();
inifile.Close();
char key[600];
DWORD bytes = GetPrivateProfileString(lpszSection,lpszEntry,def_str,key,590,path);
if(bytes < 600)
key[bytes] = ‘\0′;
sIp = key;
return sIp;
}
33.合并一个文件下所有的文件
CString Directory=%%1+”\\”+%%3;
CFileFind FFile;
CFile Out;
if(Out.Open(%%2,CFile::modeWrite|CFile::modeCreate)){
BOOL bFound=FFile.FindFile(Directory);
while(bFound)
{
bFound=FFile.FileNextFile();
if(!FFile.IsDirectory() && !FFile.IsDots())
{
CString Filename=FFile.GetFileName();
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(“不能创建输出文件”);
34.写入ini文件属性
int UGetProfileInt(CString lpszSection,CString lpszEntry,int defaultint )
{
CStdioFile inifile(“Setup.INI”,CFile::modeRead);
CString path;
path = inifile.GetFilePath();
inifile.Close();
int bytes = 0;
bytes = GetPrivateProfileInt(lpszSection,lpszEntry,defaultint,path);
return bytes;
}
35.获得当前路径
TCHAR szDir[MAX_PATH];
GetCurrentDirectory(szDir,MAX_PATH];
CString %%1(szDir);
31.文件简单解密
FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read);
byte[] btArr = new byte[fsr.Length];
fsr.Read(btArr, 0, btArr.Length);
fsr.Close();
for (int i = 0; i < btArr.Length; i++) //解密
{
int ibt = btArr[i];
ibt -= 100;
ibt += 256;
ibt %= 256;
btArr[i] = Convert.ToByte(ibt);
}
//写文件
string strFileName = Path.GetExtension(%%1);
FileStream fsw = new FileStream(%%2 +”/” + strFileName, FileMode.Create, FileAccess.Write);
fsw.Write(btArr, 0, btArr.Length);
fsw.Close();
32.读取ini文件属性
//[DllImport("kernel32")]//返回0表示失败,非0为成功
//private static extern long WritePrivateProfileString(string section,string key, string val,string filePath);
//[DllImport("kernel32")]//返回取得字符串缓冲区的长度
//private static extern long GetPrivateProfileString(string section,string key, string def,StringBuilder retVal,int size,string filePath);
public static string ReadIniData(string Section,string Key,string NoText,string iniFilePath)
{
if(File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);
return temp.ToString();
}
else
{
return String.Empty;
}
}
33.合并一个文件下所有的文件
34.写入ini文件属性
//[DllImport("kernel32")]//返回0表示失败,非0为成功
//private static extern long WritePrivateProfileString(string section,string key, string val,string filePath);
//[DllImport("kernel32")]//返回取得字符串缓冲区的长度
//private static extern long GetPrivateProfileString(string section,string key, string def,StringBuilder retVal,int size,string filePath);
public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath)
{
if(File.Exists(iniFilePath))
{
long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath);
if(OpStation == 0)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
35.获得当前路径
Environment.CurrentDirectory.ToString()
36.读取XML数据库
//#include <string>
//using namespace std;
char sRead[5192];
CFile mFile(_T(%%1),CFile::modeRead);
mFile.Read(sRead,5192);
if(sRead!=null)
{
string tmp;
while(sRead!=null)
{
tmp.append(sRead);
mFile.Read(sRead,5192);
}
//%%2=”Logs” //%%4=”ID” //%%6=”Content”
//%%3=”Log” //%%5=”Time”
//%%7 code %%8 time %%9 content
string target(%%7),globalTag(“<”+%%2+”>”);
string propTag1(“<”+%%5+”>”,endTag1(“</”+%%5+”>”);
string propTag2(“<”+%%6+”>”,endTag1(“</”+%%6+”>”);
int offset=tmp.find_first_of(globalTag);
while(offset)
{
offset=tmp.find_first_of(globalTag);
string description;
tmp.copy(description.begin(),tmp.find_first_of(“\”",offset+1)
-offset);
if(target.compare(description)==0)
{
string prop,prop2;
offset=tmp.find_first_of(propTag1,offset)+strlen(%%5)+2;
tmp.copy(prop.begin(),tmp.find_first_of(endTag1,offset)-
offset,offset);
offset=tmp.find_first_of(propTag2,offset)+strlen(%%6)+2;
tmp.copy(prop2.begin(),tmp.find_first_of(endTag2,offset)-
offset,offset);
CString %%8(prop),%%9(prop2);
%%10
return 0;
}
}
}
else
return -1;
37.写入XML数据库
//#include <string>
//using namespace std;
char sRead[5192];
string description;
CFile mFile(_T(%%1),CFile::modeRead);
mFile.Read(sRead,5192);
int no;
if(sRead!=null)
{
string tmp;
while(sRead!=null)
{
tmp.append(sRead);
mFile.Read(sRead,5192);
}
//%%2=”Logs” //%%4=”ID” //%%6=”Content”
//%%3=”Log” //%%5=”Time”
//%%7 code %%8 time %%9 content
int offset=tmp.find_last_of(“<”+%%3+” “+%%4)+strlen(%%3)
+strlen(%%4)+4;
tmp.copy(description.begin(),tmp.find_last_of(“\”><”+%%5)-
offset,offset);
bo=atoi(description.c_str())+1;
mFile.Close();
tmp.insert(tmp.find_last_of(“</”+%%2+”>”),”<”+%%3+” “+%%
4+”=\”"+itoa(no)+”\”><”+%%5+”>”+%%8+”</”+%%5+”><”+%%6+”>”+%%
9+”</”+%%6+”>”);
CFile file(_T(%%1),CFile::modeWrite);
file.Write(tmp.c_str()):
file.Flush();
file.Close();
}
else
{
CFile file(_T(%%1),CFile::modeWrite|CFile::modeCreate);
file.Write(“<?xml version=\”1.0\” encoding=\”gb2312\”?><”+%%
2+”><”+%%3+” “+%%4+”=\”0\”><”+%%5+”>”+%%8+”</”+%%5+”><”+%%
6+”>”+%%9+”</”+%%6+”></”+%%3+”></”+%%2+”>”);
file.Flush();
file.Close();
}
38.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);
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);
39.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, // 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;
//////////////////////////////////////////////////////////////
////////
//这里就是最重要的,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);
40.ZIP压缩文件夹
//www.zlib.net
/*
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <dos.h>
#include <direct.h>
#include <zlib.h>
#if defined(MSDOS) || defined(OS2) || defined(WIN32) ||
defined(__CYGWIN__)
# include <fcntl.h>
# include <io.h>
# 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;
}
// 以上就是主要的目录压缩代码,主要是将目录/文件的名称写入后,紧跟着压缩后的数据。
41.递归删除目录下的文件
CString Directory(%%1);
CStringArray csa;
int count=0;
if(Directory.Right(1)!=”\\”)
Directory+=”\\”;
Directory+=”*.*”;
CFileFInd FFile;
csa.add(Directory);
while(count<csa.GetSize())
{
if(FFile.FindFile(csa.GetAt(i)))
{
bFound=FFile.FindNextFile();
if(!FFile.IsDirectory() && !FFile.IsDots())
{
DeleteFile(FFile.GetFilePath());
}
else if(FFile.IsDirectory())
{
csa.Add(FilePath+”\\*.*”);
}
}
else
count++;
}
}
42.C++ 验证DTD
//#include <stdexcept> // runtime_error
//#include <xercesc/sax2/DefaultHandler.hpp>
using namespace std;
using namespace xercesc;
try {
// Initialize Xerces and obtain a SAX2 parser
XercesInitializer init;
auto_ptr<SAX2XMLReader>
parser(XMLReaderFactory::createXMLReader());
// Enable validation
parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
// Register error handler to receive notifications
// of DTD violations
CircusErrorHandler error;
parser->setErrorHandler(&error);
parser->parse(“animals.xml”);
} catch (const SAXException& e) {
cout << “xml error: ” << toNative(e.getMessage()) << “\n”;
return EXIT_FAILURE;
} catch (const XMLException& e) {
cout << “xml error: ” << toNative(e.getMessage()) << “\n”;
return EXIT_FAILURE;
} catch (const exception& e) {
cout << e.what() << “\n”;
return EXIT_FAILURE;
}
43.C++ Schema 验证
//#include <xercesc/sax2/XMLReaderFactory.hpp>
//#include <xercesc/sax2/SAX2XMLReader.hpp>
//#include <xercesc/sax2/DefaultHandler.hpp>
// Handy definitions of constants.
#include <xercesc/util/XMLUni.hpp>
// 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;
44.C++ 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);
}