douzhanglu4591 2015-04-08 02:52
浏览 1380
已采纳

如何在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.

  • 写回答

4条回答 默认 最新

  • duanbogan5878 2015-04-08 05:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?