代码:
#include "stdafx.h"
#include <Windows.h>
#include <tchar.h>
#define MAX_SIZE 512
int EncodeQuoted(const unsigned char* pSrc, char* pDst, int nSrcLen, int nMaxLineLen);
int DecodeQuoted(const char* pSrc, unsigned char* pDst, int nSrcLen);
int _tmain(int argc, TCHAR *argv[])
{
//MessageBox(NULL, L"a", L"a", MB_OK);
BOOL bAction;
// TCHAR tFileName = TEXT("a.txt");
// TCHAR tWriteFile = "b.txt";
char *pcBuffer = new char[MAX_SIZE];
unsigned char *pDst = new unsigned char[MAX_SIZE];
DWORD dwNumBytes = 0;
DWORD dwFileSize = 0;
HANDLE hFile = CreateFile(argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
printf("file create error (error %d)\n", GetLastError());
delete pcBuffer;
delete pDst;
pcBuffer = NULL;
pDst = NULL;
return 0;
}
// GetFileSize(hFile, &dwFileSize);
bAction = ReadFile(hFile, pcBuffer, MAX_SIZE, &dwNumBytes, NULL);
//printf("bAction is %d\n", bAction);
if(!bAction)
{
printf("file read error(error %d)\n", GetLastError());
delete pcBuffer;
delete pDst;
pDst = NULL;
pcBuffer = NULL;
CloseHandle(hFile);
return 0;
}
dwFileSize = DecodeQuoted(pcBuffer, pDst, dwNumBytes);
if(dwFileSize <= 0)
{
printf("dwFileSize is 0\n");
return 0;
}
dwNumBytes = 0;
delete pcBuffer;
pcBuffer = NULL;
CloseHandle(hFile);
HANDLE hWriteFile = CreateFile(argv[2], GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL);
if(hWriteFile == INVALID_HANDLE_VALUE)
{
printf("write file create error(error %d)\n", GetLastError());
delete pDst;
pDst = NULL;
return 0;
}
bAction = WriteFile(hWriteFile, pDst, dwFileSize, &dwNumBytes, NULL);
/*if(!bAction)
{*/
printf("write file write error(error %d)\n", GetLastError());
delete pDst;
pDst = NULL;
CloseHandle(hWriteFile);
return 0;
//}
//return 0;
}
int EncodeQuoted(const unsigned char* pSrc, char* pDst, int nSrcLen, int nMaxLineLen)
{
int nDstLen; // 输出的字符计数
int nLineLen; // 输出的行长度计数
nDstLen = 0;
nLineLen = 0;
for (int i = 0; i < nSrcLen; i++, pSrc++)
{
// ASCII 33-60, 62-126原样输出,其余的需编码
if ((*pSrc >= '!') && (*pSrc <= '~') && (*pSrc != '='))
{
*pDst++ = (char)*pSrc;
nDstLen++;
nLineLen++;
}
else
{
sprintf_s(pDst, MAX_SIZE, "=%02X", *pSrc);
pDst += 3;
nDstLen += 3;
nLineLen += 3;
}
// 输出换行?
if (nLineLen >= nMaxLineLen - 3)
{
sprintf_s(pDst, MAX_SIZE, "=\r\n");
pDst += 3;
nDstLen += 3;
nLineLen = 0;
}
}
// 输出加个结束符
*pDst = '\0';
return nDstLen;
}
//Quoted-Printable解码很简单,将编码过程反过来就行了。
int DecodeQuoted(const char* pSrc, unsigned char* pDst, int nSrcLen)
{
int nDstLen; // 输出的字符计数
int i;
i = 0;
nDstLen = 0;
while (i < nSrcLen)
{
if (strncmp(pSrc, "=\r\n", 3) == 0) // 软回车,跳过
{
pSrc += 3;
i += 3;
}
else
{
if (*pSrc == '=') // 是编码字节
{
sscanf_s(pSrc, "=%02X", pDst);
pDst++;
pSrc += 3;
i += 3;
}
else // 非编码字节
{
*pDst++ = (unsigned char)*pSrc++;
i++;
}
nDstLen++;
}
}
// 输出加个结束符
// *pDst = '\0';
return nDstLen;