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

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

图片转代码服务由CSDN问答提供 功能建议

使用Python,我可以执行下一个操作:

  equals =  filecmp.cmp(file_old,file_new)
   
 
 

是否有任何内置函数可以用go语言来做到这一点? 我用谷歌搜索,但没有成功。

我可以在 hash / crc32 包中使用一些哈希函数,但这要比上面的Python代码更多。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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条)