美文网首页
swift 获取文件的Md5值

swift 获取文件的Md5值

作者: 昨天的李小白 | 来源:发表于2017-07-25 16:40 被阅读0次
    func md5File(url: URL) -> String? {
            
            let bufferSize = 1024 * 1024
            
            do {
                //打开文件
                let file = try FileHandle(forReadingFrom: url)
                defer {
                    file.closeFile()
                }
                
                //初始化内容
                var context = CC_MD5_CTX()
                CC_MD5_Init(&context)
                
                //读取文件信息
                while case let data = file.readData(ofLength: bufferSize), data.count > 0 {
                    data.withUnsafeBytes {
                        _ = CC_MD5_Update(&context, $0, CC_LONG(data.count))
                    }
                }
                
                //计算Md5摘要
                var digest = Data(count: Int(CC_MD5_DIGEST_LENGTH))
                digest.withUnsafeMutableBytes {
                    _ = CC_MD5_Final($0, &context)
                }
                
                return digest.map { String(format: "%02hhx", $0) }.joined()
                
            } catch {
                print("Cannot open file:", error.localizedDescription)
                return nil
            }
        }
    

    相关文章

      网友评论

          本文标题:swift 获取文件的Md5值

          本文链接:https://www.haomeiwen.com/subject/natgkxtx.html