获取文件CRC32值VC++实现。。。。。

类别:VC语言 点击:0 评论:0 推荐:

[转载请注明出处]

首先在头文件里面申明一下:    unsigned long Crc32Table[256];

代码开始:

void CGetCrcDlg::OnGetFileCrc() //打开文件然后在EDIT控件里面直接显示文件校验值;
{
 HANDLE hFile = {NULL};
 DWORD dwSize, bytes_read;
 CString FileNameStr;
   
 MakeTable();//生成码表

    //打开对话框
 CFileDialog dlg(TRUE, NULL, "", OFN_HIDEREADONLY,
    "All Files (*.*)|*.*||", this);
    if(IDOK != dlg.DoModal())
      return;

    FileNameStr = dlg.GetPathName();

 hFile = CreateFile(FileNameStr, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
  NULL, OPEN_EXISTING,
  FILE_FLAG_SEQUENTIAL_SCAN, NULL);
 dwSize = GetFileSize(hFile, NULL);

 CString csData(' ', dwSize);
 ReadFile(hFile, csData.GetBuffer(dwSize), dwSize, &bytes_read, NULL);
 CloseHandle(hFile);
 csData.ReleaseBuffer();

 int nCRC = Get_CRC(csData, dwSize);
 char ch[20];
 itoa(nCRC, ch, 16); 
 m_FileCrcValue= ch;
 m_FileCrcValue.MakeUpper();
 UpdateData(FALSE);
}

void CGetCrcDlg::MakeTable()//动态生成CRC32的码表
{
   int i,j;
   unsigned long crc;
   for (i = 0; i < 256; i++)
    {
        crc = i;
        for (j = 0; j < 8; j++)
        {
            if (crc & 1)
                crc = (crc >> 1) ^ 0xEDB88320;
            else
                crc >>= 1;
        }
        Crc32Table[i] = crc;
    }
}

int CGetCrcDlg::Get_CRC(CString &csData, DWORD dwSize)//获取crc32值
{
 ULONG  crc(0xffffffff);
 int len;
 unsigned char* buffer;
 len = dwSize;
 buffer = (unsigned char*)(LPCTSTR)csData;
 while(len--)
  crc = (crc >> 8) ^ Crc32Table[(crc & 0xFF) ^ *buffer++];
 return crc^0xffffffff;
}

[转载请注明出处]

本文地址:http://com.8s8s.com/it/it14.htm