Go Text File Compare Hash

Introduction

A common use for crc32 is to compare two files.

If the Sum32 value for both files is the same, it's highly likely that the files are the same.

If the values are different, then the files are definitely not the same:



package main //from   www. ja va  2 s .co  m

import ( 
    "fmt" 
    "hash/crc32" 
    "os" 
    "io" 
) 

func getHash(filename string) (uint32, error) { 
    // open the file 
    f, err  := os.Open(filename) 
    if err  != nil { 
        return 0, err 
    } 
    // remember to always close opened files 
    defer f.Close() 

    // create a hasher 

    h := crc32.NewIEEE() 
    // copy the file into the hasher 
    // - copy takes (dst, src) and returns (bytesWritten, error) 
    _, err  = io.Copy(h, f) 
    // we don't care about how many bytes were written, but we do want to 
    // handle the error 
    if err  != nil { 
      return 0, err 
    } 
    return h.Sum32(), nil 
} 

func main() { 
    h1, err  := getHash("main.go") 
    if err  != nil { 
        return 
    } 
    h2, err2 := getHash("main.go") 
    if err2  != nil { 
        return 
    } 
    fmt.Println(h1, h2, h1 == h2) 
} 



PreviousNext

Related