MDGSF Software Engineer

[GO] 生成当前目录下文件的MD5值

2017-10-19
GO

package main

import (
    "crypto/md5"
    "flag"
    "fmt"
    "io"
    "log"
    "os"
    "os/exec"
    "path/filepath"
    "time"
)

const PROGRAM_NAME = "genMd5.exe"
const RESULT_NAME = "md5result.txt"

func isDir(path string) bool {
    fileInfo, err := os.Stat(path)
    if err != nil {
        fmt.Println("os.Stat failed", err.Error())
        return false
    }
    return fileInfo.IsDir()
}

func genMd5File(path string) []byte {
    f, err := os.Open(path)
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    h := md5.New()
    if _, err := io.Copy(h, f); err != nil {
        log.Fatal(err)
    }

    fileMd5 := h.Sum(nil)
    //fmt.Printf("%x\n", fileMd5)
    return fileMd5
}

func getCurrentPath() (RelativePath string, AbsolutePath string, err error) {
    RelativePath = filepath.Dir(os.Args[0])
    file, _ := exec.LookPath(os.Args[0])
    ApplicationPath, _ := filepath.Abs(file)
    AbsolutePath, _ = filepath.Split(ApplicationPath)
    return
}

var writeToFile = flag.Bool("writeToFile", false, "Write md5 result to file.")

func main() {
    //fmt.Println(os.Args[0])
    //fmt.Println(getCurrentPath())
    //genMd5File("U3DXueZhanDaoDi.dll")

    flag.Parse()

    var f *os.File
    var err error
    if *writeToFile {
        f, err = os.OpenFile(RESULT_NAME, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
        if err != nil {
            fmt.Println(err)
            return
        }
        defer f.Close()

        f.WriteString(time.Now().String())
        f.WriteString("\r\n")
    }

    relativePath, absolutePaht, _ := getCurrentPath()
    fmt.Println(relativePath, absolutePaht)

    dir, err := os.Open(absolutePaht)
    if err != nil {
        fmt.Println("os.Open failed", err.Error())
        return
    }
    defer dir.Close()

    names, err := dir.Readdirnames(-1)
    if err != nil {
        fmt.Println("dir.Readdirnames failed", err.Error())
        return
    }

    for _, name := range names {
        sub := absolutePaht + "\\" + name
        if isDir(sub) {
            continue
        }
        if name == PROGRAM_NAME {
            continue
        }
        if name == RESULT_NAME {
            continue
        }

        fileMd5 := genMd5File(sub)
        str := fmt.Sprintf("%s:%x\r\n", name, fileMd5)
        if *writeToFile {
            f.WriteString(str)
        } else {
            fmt.Printf("%s:%x\n", name, fileMd5)
        }
    }

    if !*writeToFile {
        var done int
        fmt.Scanf("%d", done)
    }
}

weixingongzhonghao

Comments

Content