On the Linux machine, there is a command to calculate the MD5 value of the file, that is md5sum, if not, you need to install the RPM package: Coreutils.
Now we can also easily compute the MD5 value of the file using the OpenSSL library. The main function to use is
int Md5_init (Md5_ctx *c);
int Md5_update (md5_ctx *c, const void *data, size_t len);
int md5_final (unsigned char *md, md5_ctx *c);
Before using the library, you need to install the OpenSSL RPM package first. These three functions do not need to be explained, see the following example to know:
#include <openssl/md5.h> #include <iostream> #include <cstdio> #include <iomanip> using
namespace Std;
int main () {FILE *fd=fopen ("test", "R");
Md5_ctx C;
unsigned char md5[17]={0};
if (fd = NULL) {cout << "open failed" << Endl;
return-1;
int Len;
unsigned char *pdata = (unsigned char*) malloc (1024*1024*1024);
if (!pdata) {cout << "malloc failed" << Endl;
return-1;
} md5_init (&C);
while (0!= (len = fread (PData, 1, 1024*1024*1024, FD)) {md5_update (&c, PData, Len);
} md5_final (MD5,&C); for (int i = 0; i < i++) cout << hex << setw (2) << Setfill (' 0 ') << (int) md5[
I];
cout << Endl;
Fclose (FD);
Free (pData);
return 0; }
The compile link options are:
g++ Test.cpp-o Testmd5-lcrypto-lssl
After generating the testmd5, we put a test file of more than 300 m into a directory with TESTMD5. And comparing the results generated by TESTMD5 with the results of the Linux command "md5sum test", you will find the same.
int GetFileMD5 (std::string strfile, std::string& strMD5) {int nlen = 0;
unsigned int nbuffersize = 1024 * 1024;
Char sztemp[4];
unsigned char szmd5[20];
Md5_ctx CTX;
Set buffer size by file size Ace_stat stfileinfo;
memset (&stfileinfo, 0, sizeof (ACE_STAT));
Nret = Ace_os::lstat (Strfile.c_str (), &stfileinfo);
if (nret!= 0) {printf ("Stat file error[%s].\n", Strfile.c_str ());
return-1;
} if (Stfileinfo.st_size < nbuffersize) {nbuffersize = stfileinfo.st_size + 64;
}//Open file File *FP = fopen (Strfile.c_str (), "R");
if (fd = NULL) {printf ("fopen error:%s.\n", Strfile.c_str ());
return-1;
} unsigned char *pdatabuffer = (unsigned char*) malloc (nbuffersize);
if (NULL = = Pdatabuffer) {printf ("malloc error:%d.\n", nbuffersize);
Fclose (FP) return-1;
}//Get MD5 md5_init (&CTX);
while (true) {memset (pdatabuffer, 0, nbuffersize);
Nlen = Fread (Pdatabuffer, 1, nbuffersize, FP);
if (Nlen = = 0) {break; } md5_upDate (&ctx, Pdatabuffer, Nlen);
} md5_final (SzMD5, &ctx);
MD5 to string strMD5 = "";
for (int i = 0; i < i++) {memset (sztemp, 0, sizeof (sztemp));
snprintf (sztemp, sizeof (sztemp), "%02x", (int) szmd5[i]);
StrMD5 + = sztemp;
Fclose (FP);
if (NULL!= pdatabuffer) {free (pdatabuffer);
Pdatabuffer = NULL;
return 0;
}