MFC文件操作大全(二)

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<PartLength)
break;
nCount++;
}
m_File.Close();
}
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;
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 <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;
}
 

32.文件简单解密

//#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;
}

33.读取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;
}

34.合并一个文件下所有的文件

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("不能创建输出文件");

35.写入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;
}

36.获得当前路径

TCHAR szDir[MAX_PATH];
GetCurrentDirectory(szDir,MAX_PATH];
CString %%1(szDir);

37.读取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;

38.写入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();
}

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);
 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"); // processerror
  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);

41.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;
}

// 以上就是主要的目录压缩代码,主要是将目录/文件的名称写入后,紧跟着压缩后的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值