Obtaining the MD5 Hash of a File in C
To determine the MD5 hash of a file, one can utilize the following steps:
Step 1: Establish File Descriptor and Determine File Size
Using the open() function, acquire a file descriptor for the target file. Subsequently, utilize the fstat() function to determine the file's size.
Step 2: Map File into Memory
Employ the mmap() function to map the file into memory, providing read-only access. This mapping facilitates direct access to the file's contents.
Step 3: Compute MD5 Hash
Utilizing the OpenSSL library, invoke the MD5() function to compute the MD5 hash of the file's contents.
Step 4: Unmap File from Memory
Once the MD5 hash has been computed, employ the munmap() function to unmap the file from memory. This step releases the file mapping.
Step 5: Print MD5 Hash with File Name
Display the computed MD5 hash along with the corresponding file name for reference.
The following C code snippet demonstrates this process:
#include <openssl/md5.h> void computeMD5(const char* filename) { // Establish file descriptor and determine file size int fd = open(filename, O_RDONLY); struct stat statbuf; fstat(fd, &statbuf); size_t file_size = statbuf.st_size; // Map file into memory char* file_buffer = (char*)mmap(0, file_size, PROT_READ, MAP_SHARED, fd, 0); // Compute MD5 hash unsigned char md5[MD5_DIGEST_LENGTH]; MD5((unsigned char*)file_buffer, file_size, md5); // Unmap file from memory munmap(file_buffer, file_size); // Print MD5 hash with file name printf("MD5 hash of '%s': ", filename); for (int i = 0; i < MD5_DIGEST_LENGTH; i++) { printf("%02x", md5[i]); } printf("\n"); }
The above is the detailed content of How to Calculate the MD5 Hash of a File using C ?. For more information, please follow other related articles on the PHP Chinese website!