How to read certain lines in a file and tell what is different
Hello,
I have 2 files that I am going to compare. I was wondering how would I go about to read those files, and tell what is different. Take for instance...that file1.txt has <name>Fred</Fred>
<name>Barney</name>
<name>This</name>
File2.txt has...
<name> Barn</name>
<name> Fred</name>
<name> This</name>
Then I would have file box say file2.txt is different than file1.txt.
Because it has more names than than file1.txt and also file2.txt is missing barney.
Can someone tell me of a website that can help me with this, or can they help me themselves?
Re: How to read certain lines in a file and tell what is different
I have done this a while ago... it's a bit "clumsy", but it'll do - i'm sure it can be done easier, but hey ;)
VB Code:
Dim arr1() As String, arr2() As String, arrDifferent() As String, line As String
Dim i As Integer, j As Integer, n As Integer, k As Integer, _
counter As Integer, diffCounter As Integer, FF As Integer
i = -1: FF = FreeFile
'load first file
Open "c:\first.txt" For Input As #FF
Do Until EOF(FF)
i = i + 1
Line Input #FF, line
line = LTrim(line): line = RTrim(line)
If line <> vbNullString Then
ReDim Preserve arr1(i) As String
arr1(i) = line
Else
i = i - 1
End If
Loop
Close #FF
i = -1: FF = FreeFile
'load second file
Open "c:\second.txt" For Input As #FF
Do Until EOF(FF)
i = i + 1
Line Input #FF, line
line = LTrim(line): line = RTrim(line)
If line <> vbNullString Then
ReDim Preserve arr2(i) As String
arr2(i) = line
Else
i = i - 1
End If
Loop
Close #FF
n = -1: diffCounter = 0
'compare in one way
For i = 0 To UBound(arr1)
counter = 0
For j = 0 To UBound(arr2)
If arr1(i) = arr2(j) Then
counter = counter + 1
Exit For
End If
Next j
If counter = 0 Then
n = n + 1
diffCounter = diffCounter + 1
ReDim Preserve arrDifferent(n) As String
arrDifferent(n) = arr1(i)
End If
Next i
'compare in second way
For i = 0 To UBound(arr2)
counter = 0
For j = 0 To UBound(arr1)
If arr2(i) = arr1(j) Then
counter = counter + 1
Exit For
End If
Next j
If counter = 0 Then
n = n + 1: counter = 0
If diffCounter <> 0 Then
For k = 0 To UBound(arrDifferent)
If arrDifferent(k) = arr2(i) Then
counter = counter + 1
Exit For
End If
Next k
If counter = 0 Then
diffCounter = diffCounter + 1
ReDim Preserve arrDifferent(UBound(arrDifferent) + 1) As String
arrDifferent(UBound(arrDifferent)) = arr2(i)
End If
Else
diffCounter = diffCounter + 1
ReDim Preserve arrDifferent(0) As String
arrDifferent(UBound(arrDifferent)) = arr2(i)
End If
End If
Next i
'display all the different ones... if there are any
If diffCounter <> 0 Then
For i = 0 To UBound(arrDifferent)
Debug.Print arrDifferent(i)
Next i
Else
MsgBox "There is no difference!"
End If