GolangNote

Golang笔记

Golang 实现md5sum 计算文件md5 值

Permalink

Golang 实现md5sum 分片计算大文件md5 值

Go: md5sum 计算文件md5 值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main

import (
	"crypto/md5"
	"fmt"
	"io"
	"math"
	"os"
)

const fileChunk = 8192 // 8KB

func countFileMd5(filePath string) string {
	file, err := os.Open(filePath)
	if err != nil {
		return err.Error()
	}
	defer file.Close()

	info, _ := file.Stat()
	fileSize := info.Size()

	blocks := uint64(math.Ceil(float64(fileSize) / float64(fileChunk)))
	hash := md5.New()

	for i := uint64(0); i < blocks; i++ {
		blockSize := int(math.Min(fileChunk, float64(fileSize-int64(i*fileChunk))))
		buf := make([]byte, blockSize)

		file.Read(buf)
		io.WriteString(hash, string(buf))
	}

	return fmt.Sprintf("%x", hash.Sum(nil))
}

func main() {
	if len(os.Args) == 1 {
		fmt.Println("run with one or more file path")
		fmt.Println("eg: md5sum a.txt b.txt c.iso")
		return
	}
	for i := 1; i < len(os.Args); i++ {
		fmt.Println(countFileMd5(os.Args[i]), os.Args[i])
	}
}

本文网址: https://golangnote.com/topic/214.html 转摘请注明来源

Related articles

Write a Comment to "Golang 实现md5sum 计算文件md5 值"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.17.1 Processed in 0ms