代码如下:
+(NSString*)getFileMD5WithPath:(NSString*)path
{
return(__bridge_transferNSString*)FileMD5HashCreateWithPath((__bridgeCFStringRef)path,FileHashDefaultChunkSizeForReadingData);
}
CFStringRefFileMD5HashCreateWithPath(CFStringReffilePath,size_tchunkSizeForReadingData) {
// Declare needed variables
CFStringRefresult =NULL;
CFReadStreamRefreadStream =NULL;
// Get the file URL
CFURLReffileURL =
CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
(CFStringRef)filePath,
kCFURLPOSIXPathStyle,
(Boolean)false);
if(!fileURL)gotodone;
// Create and open the read stream
readStream =CFReadStreamCreateWithFile(kCFAllocatorDefault,
(CFURLRef)fileURL);
if(!readStream)gotodone;
booldidSucceed = (bool)CFReadStreamOpen(readStream);
if(!didSucceed)gotodone;
// Initialize the hash object
CC_MD5_CTXhashObject;
CC_MD5_Init(&hashObject);
// Make sure chunkSizeForReadingData is valid
if(!chunkSizeForReadingData) {
chunkSizeForReadingData =FileHashDefaultChunkSizeForReadingData;
}
// Feed the data to the hash object
boolhasMoreData =true;
while(hasMoreData) {
uint8_tbuffer[chunkSizeForReadingData];
CFIndexreadBytesCount =CFReadStreamRead(readStream,(UInt8*)buffer,(CFIndex)sizeof(buffer));
if(readBytesCount == -1)break;
if(readBytesCount ==0) {
hasMoreData =false;
continue;
}
CC_MD5_Update(&hashObject,(constvoid*)buffer,(CC_LONG)readBytesCount);
}
// Check if the read operation succeeded
didSucceed = !hasMoreData;
// Compute the hash digest
unsignedchardigest[CC_MD5_DIGEST_LENGTH];
CC_MD5_Final(digest, &hashObject);
// Abort if the read operation failed
if(!didSucceed)gotodone;
// Compute the string result
charhash[2*sizeof(digest) +1];
for(size_ti =0; i
snprintf(hash + (2* i),3,"%02x", (int)(digest[i]));
}
result =CFStringCreateWithCString(kCFAllocatorDefault,(constchar*)hash,kCFStringEncodingUTF8);
done:
if(readStream) {
CFReadStreamClose(readStream);
CFRelease(readStream);
}
if(fileURL) {
CFRelease(fileURL);
}
returnresult;
}