Search code examples
gofile-comparisonfilecompare

How can I compare two files in golang?


With Python I can do the next:

equals = filecmp.cmp(file_old, file_new)

Is there any builtin function to do that in go language? I googled it but without success.

I could use some hash function in hash/crc32 package, but that is more work that the above Python code.


Solution

  • I am not sure that function does what you think it does. From the docs,

    Unless shallow is given and is false, files with identical os.stat() signatures are taken to be equal.

    Your call is comparing only the signature of os.stat, which only includes:

    1. File mode
    2. Modified Time
    3. Size

    You can learn all three of these things in Go from the os.Stat function. This really would only indicate that they are literally the same file, or symlinks to the same file, or a copy of that file.

    If you want to go deeper you can open both files and compare them (python version reads 8k at a time).

    You could use an crc or md5 to hash both files, but if there are differences at the beginning of a long file, you want to stop early. I would recommend reading some number of bytes at a time from each reader and comparing with bytes.Compare.