Pages

Tuesday, 18 October 2011

Compare the contents of two text files.


' =============================================================
' function: CompareFiles
' desc :    Compares two text files
' params :  strFile1 is the first file
'           strFile2 is the second file
' returns : True if they are the same, False otherwise
' =============================================================
Function CompareFiles(strFile1strFile2)

Dim objFS
Dim objFileAobjFileB
Dim strLineAstrLineB
dim intCompareResult

' create a file scripting object
Set objFS = CreateObject("Scripting.FileSystemObject")

' open each of the files for reading
Set objFileA = objFS.OpenTextFile(strFile11)
Set objFileB = objFS.OpenTextFile(strFile21)

' repeat the following until we hit the end of one of the files
Do While ((objFileA.AtEndOfStream <> TrueOR (objFileB.AtEndOfStream <> True))

    ' read the next line from both files
    strLineA = objFileA.ReadLine
    strLineB = objFileB.ReadLine

    ' perform a comparison on the line from each file
    intCompareResult = StrComp(strLineA,strLineB,0)

    ' if the value of the comparison is not 0, lines are different
    If (intCompareResult <> 0Then

        ' found a difference in the files, so close them both
        objFileA.Close
        objFileB.Close

        ' destroy the object
        Set objFS = Nothing

        ' return false
        CompareFiles = False

        ' exit the function
        Exit Function

    End If ' if different

Loop ' until end of file

' close both files
objFileA.Close
objFileB.Close

' destroy the object
Set objFS = Nothing

' if function got this far, means files are the same, so return True
CompareFiles = True

End Function 'CompareFiles



0 comments:

Post a Comment