Page 1 of 1

How to check if two files are identical

Posted: Tuesday 9th January 2024 7:08am
by pusherman
Hi all

Is there a way to check if two files are identical?

I notice that there is a gb.Hash class where you can get a hash value of some specified text, but this doesn't give the hash value of a specified file.

I want to be able to say;
a=hash(file1)
b=hash(file2)

does a=b?

Thanks for looking

Re: How to check if two files are identical

Posted: Tuesday 9th January 2024 10:30am
by thatbruce
The quick answer is to shell out to the standard "diff" utility, using the "-s" option. This save you having to load the files. (More later, I'm a bit tired)
b

Re: How to check if two files are identical

Posted: Tuesday 9th January 2024 4:27pm
by cogier
I agree with thatbruce. The diff command will do what you need. Have a look at the code below.

Public Sub Form_Open()
  
  Dim sFile1 As String = User.Home &/ "Diff1"
  Dim sFile2 As String = User.Home &/ "Diff2"
  Dim sResult As String
  
  Shell "diff " & sFile1 & " " & sFile2 To sResult
  
  If Trim(sResult) = "" Then  
    Print "Files are the same"
  Else
    Print "Files are different"
  End If 
  
End

Re: How to check if two files are identical

Posted: Tuesday 9th January 2024 6:39pm
by vuott
The native Comp() function may also be fine, , loading the two files with the "File.Save()" Method.
http://gambaswiki.org/wiki/lang/comp


If you want to check the equality of two files using the external functions of the libgio API:
https://www.gambas-it.org/wiki/index.ph ... _di_libgio


Of course, you could also write an "ad hoc " function:
Private Function Compare(pathfile1 As String, pathfile2 As String) As Boolean
 
  Dim s1, s2 As String
  Dim i As Integer
  Dim bo As Boolean = True
  
  s1 = File.Load(pathfile1)
  s2 = File.Load(pathfile2)

  If s1.Len <> s2.Len Then 
    bo = False
  Else 
    For i = 0 To s1.Len - 1
      If s1[i] <> s2[i] Then bo = False
    Next
  Endif

  Return bo

End

Re: How to check if two files are identical

Posted: Wednesday 10th January 2024 8:42am
by pusherman
Both options work, I'll toss a coin to decide which one to use :D

Thanks for your time.

Pusherman