Visual Basic Codes
ActiveX
Miscellaneous
Applications
Code Snippets
Common Dialogs
Special Effects
Database Stuff
Date Time
Files Drives
Forms
Graphics Games
Internet Stuff
Multimedia
Other
Strings
Windows
Visual Basic > Files Directories Drives sample source codes
Comparing the contents of two files
Comparing the contents of two files The following function compares the contents of two files (of any type). Note, a demonstration routine can be found at the bottom of this post: 'Purpose : Compares the content of two files (compares any type of file) 'Inputs : sFile1 The path and file name of the first file to compare. ' sFile2 The path and file name of the second file to compare. 'Outputs : Returns 0 if the files are different. ' 1 if the files are identical. ' -1 if an error occurred. 'Notes : 'Revisions : Function FileCompare(sFile1 As String, sFile2 As String) As Long Const clChunkSize As Long = 1000 Dim iFile1 As Integer, iFile2 As Integer Dim lNumChunks As Long, lRemaining As Long, lThisChunk As Long Dim sBuffer1 As String * clChunkSize Dim sBuffer2 As String * clChunkSize If Len(Dir$(sFile1)) > 0 And Len(Dir$(sFile2)) > 0 Then On Error GoTo ErrFailed iFile1 = FreeFile Open sFile1 For Binary Access Read As iFile1 iFile2 = FreeFile Open sFile2 For Binary Access Read As iFile2 If LOF(iFile1) <> LOF(iFile2) Then 'Files are a different size FileCompare = 0 Else 'Files are same size lNumChunks = LOF(iFile1) \ clChunkSize lRemaining = LOF(iFile1) Mod clChunkSize 'Remaining number of bytes 'Loop over the files reading in chunks of data and compairing them For lThisChunk = 1 To lNumChunks Get iFile1, clChunkSize * (lThisChunk - 1) + 1, sBuffer1 Get iFile2, clChunkSize * (lThisChunk - 1) + 1, sBuffer2 If Not sBuffer1 = sBuffer2 Then 'Files are different FileCompare = 0 Exit For End If Next If lThisChunk = lNumChunks + 1 Then 'Check last chunk of data Get iFile1, (clChunkSize * lNumChunks) + 1, sBuffer1 'get the remaining bytes at the end Get iFile2, (clChunkSize * lNumChunks) + 1, sBuffer2 'get the remaining bytes at the end If Not Left$(sBuffer1, lRemaining) = Left$(sBuffer2, lRemaining) Then 'Files are different FileCompare = 0 Else 'File are identical FileCompare = 1 End If End If End If 'Close files Close iFile1 Close iFile2 Else 'Files don't exist FileCompare = -1 End If Exit Function ErrFailed: 'Err occurred FileCompare = -1 End Function 'Demonstration routine Sub Test() Dim lRet As Long lRet = FileCompare("C:\Copy of Test.txt", "C:\test.txt1") If lRet = 0 Then MsgBox "Files are different", vbInformation ElseIf lRet = 1 Then MsgBox "Files are identical", vbInformation Else MsgBox "Error Failed!", vbInformation End If End Sub
Privacy Policy
|
Link to Us
|
Links