# How to obtain the result of a diff between 2 files in a loop?

**URL:** <https://discourse.julialang.org/t/how-to-obtain-the-result-of-a-diff-between-2-files-in-a-loop/23784>\
**Category:** General Usage\
**Created:** [May 2, 2019, 5:00pm UTC](https://discourse.julialang.org/t/how-to-obtain-the-result-of-a-diff-between-2-files-in-a-loop/23784 "2019-05-02T17:00:10Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [May 3, 2019, 1:38am UTC](https://discourse.julialang.org/t/how-to-obtain-the-result-of-a-diff-between-2-files-in-a-loop/23784/4 "2019-05-03T01:38:15Z")

</div>

> [@StefanKarpinski](#):
>
> `if success(`cmp --quiet file_a file_b`)`

`--quiet` is a GNU-ism; if you want it to work with any POSIX `cmp` you should use `-s`.

Of course, this won’t work on Windows. It would be pretty easy to write an equivalent Julia function, though, like:

```julia
function filecmp(path1::AbstractString, path2::AbstractString)
    stat1, stat2 = stat(path1), stat(path2)
    if !(isfile(stat1) && isfile(stat2)) || filesize(stat1) != filesize(stat2)
        return false # or should it throw if a file doesn't exist?
    end
    stat1 == stat2 && return true # same file
    open(path1, "r") do file1
        open(path2, "r") do file2
            buf1 = Vector{UInt8}(undef, 32768)
            buf2 = similar(buf1)
            while !eof(file1) && !eof(file2)
                n1 = readbytes!(file1, buf1)
                n2 = readbytes!(file2, buf2)
                n1 != n2 && return false
                0 != Base._memcmp(buf1, buf2, n1) && return false
            end
            return eof(file1) == eof(file2)
        end
    end
end

```

Not only is this more portable, it is also _much_ faster than executing an external program like `cmp`. On my Mac laptop it is about 1000× faster in the common case where the file sizes differ, and about 60× faster for a 20kB file when the files match (so that the whole files need to be read).

(Python provides [`filecmp.cmp`](https://docs.python.org/3.7/library/filecmp.html) in its standard library, I wonder if Julia should too?)

---

_[View the full topic](https://discourse.julialang.org/t/how-to-obtain-the-result-of-a-diff-between-2-files-in-a-loop/23784)._
