iOS开发,利用文件流,算大文件的MD5值(程序不会导致内存崩溃)
2013-06-28 15:10
543 查看
CFStringRef FileMD5HashCreateWithPath(CFStringRef filePath, size_t chunkSizeForReadingData) { // Declare needed variables CFStringRef result = NULL; CFReadStreamRef readStream = NULL; // Get the file URL CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)filePath, kCFURLPOSIXPathStyle, (Boolean)false); if (!fileURL) goto done; // Create and open the read stream readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, (CFURLRef)fileURL); if (!readStream) goto done; bool didSucceed = (bool)CFReadStreamOpen(readStream); if (!didSucceed) goto done; // Initialize the hash object CC_MD5_CTX hashObject; CC_MD5_Init(&hashObject); // Make sure chunkSizeForReadingData is valid if (!chunkSizeForReadingData) { chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData; } // Feed the data to the hash object bool hasMoreData = true; while (hasMoreData) { uint8_t buffer[chunkSizeForReadingData]; CFIndex readBytesCount = CFReadStreamRead(readStream, (UInt8 *)buffer, (CFIndex)sizeof(buffer)); if (readBytesCount == -1) break; if (readBytesCount == 0) { hasMoreData = false; continue; } CC_MD5_Update(&hashObject,(const void *)buffer,(CC_LONG)readBytesCount); } // Check if the read operation succeeded didSucceed = !hasMoreData; // Compute the hash digest unsigned char digest[CC_MD5_DIGEST_LENGTH]; CC_MD5_Final(digest, &hashObject); // Abort if the read operation failed if (!didSucceed) goto done; // Compute the string result char hash[2 * sizeof(digest) + 1]; for (size_t i = 0; i < sizeof(digest); ++i) { snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i])); } result = CFStringCreateWithCString(kCFAllocatorDefault, (const char *)hash, kCFStringEncodingUTF8); done: if (readStream) { CFReadStreamClose(readStream); CFRelease(readStream); } if (fileURL) { CFRelease(fileURL); } return result; } +(NSString*)fileMD5:(NSString*)path { return (__bridge_transfer NSString *)FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData); }
相关文章推荐
- iOS 同一页面加载上百张图片,迅速滑动时导致内存暴涨程序崩溃的参考解决方法
- iOS学习Core Data文件操作中调用NSManagedObjectContext类实例save:方法导致程序崩溃
- iOS开发蓝牙固件升级使用iOSDFULibrary程序崩溃的解决办法
- iOS开发- 文件共享(利用iTunes导入文件, 并且显示已有文件)
- 从C#到Objective-C,循序渐进学习苹果开发(5)--利用XCode来进行IOS的程序开发
- ios按钮点击导致程序崩溃
- 在linux下利用程序崩溃后的core文件分析bug
- 多释放一次内存导致程序不会退出??
- iOS开发 - 完美解决SDWebImage加载多个图片内存崩溃的问题
- 利用map文件找到程序崩溃代码行
- iOS开发- 文件共享(利用iTunes导入文件, 并且显示已有文件)
- iOS开发中程序崩溃邮件通知代码
- iOS开发何如在调试的时候轻松找到程序在哪里崩溃
- iOS之利用runtime,避免可变数组和可变字典为nil或者数组越界导致的崩溃
- iOS开发:UITableView加载多张照片导致内存上涨的问题
- 在linux下利用程序崩溃后的core文件分析bug
- iOS开发何如在调试的时候轻松找到程序在哪里崩溃
- 应用待机时间过长导致内存被回收程序崩溃
- 【Abode Air程序开发】iOS证书(.p12)和描述文件(.mobileprovision)申请
- iOS开发- 文件共享(利用iTunes导入文件, 并且显示已有文件)