How to check if two files are identical

New to Gambas? Post your questions here. No question is too silly or too simple.
Post Reply
pusherman
Posts: 16
Joined: Sunday 5th November 2023 11:45am

How to check if two files are identical

Post 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
User avatar
thatbruce
Posts: 168
Joined: Saturday 4th September 2021 11:29pm

Re: How to check if two files are identical

Post 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
Have you ever noticed that software is never advertised using the adjective "spreadable".
Online
User avatar
cogier
Site Admin
Posts: 1127
Joined: Wednesday 21st September 2016 2:22pm
Location: Guernsey, Channel Islands

Re: How to check if two files are identical

Post 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
vuott
Posts: 263
Joined: Wednesday 5th April 2017 6:07pm
Location: European Union

Re: How to check if two files are identical

Post 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
Europaeus sum !

Amare memorentes atque deflentes ad mortem silenter labimur.
pusherman
Posts: 16
Joined: Sunday 5th November 2023 11:45am

Re: How to check if two files are identical

Post by pusherman »

Both options work, I'll toss a coin to decide which one to use :D

Thanks for your time.

Pusherman
Post Reply