Using an interface class


Sub FilterTextFile(filter As IFilter)
 
    BugAssert filter.Source <> sEmpty
    ' Target can be another file or replacement of current file
    Dim sTarget As String, fReplace As Boolean
    sTarget = filter.Target
    If sTarget = sEmpty Or sTarget = filter.Source Then
        sTarget = MUtility.GetTempFile("FLT", ".")
        fReplace = True
    End If
 
    ' Open input file
    On Error GoTo FilterTextError1
    Dim nIn As Integer, nOut As Integer
    nIn = FreeFile
    Open filter.Source For Input Access Read Lock Write As #nIn
 
    ' Open target output file
    On Error GoTo FilterTextError2
    nOut = FreeFile
    Open sTarget For Output Access Write Lock Read Write As #nOut
 
    ' Filter each line
    On Error GoTo FilterTextError3
    Dim sLine As String, iLine As Long, eca As EChunkAction
    Do Until EOF(nIn)
        Line Input #nIn, sLine
        iLine = iLine + 1
        eca = filter.Translate(sLine, iLine)
        Select Case eca
        Case ecaAbort
            GoTo FilterTextError3   ' Stop processing
        Case ecaTranslate
            Print #nOut, sLine      ' Write modified line to output
        Case ecaSkip
                                    ' Ignore
        Case Else
            BugAssert True          ' Should never happen
        End Select
    Loop
 
    ' Close files
    On Error GoTo FilterTextError1
    Close nIn
    Close nOut
    If fReplace Then
        ' Destroy old file and replace it with new one
        Kill filter.Source
        On Error Resume Next   ' No more errors allowed
        Name sTarget As filter.Source
        ' If this fails, you’re in trouble
        BugAssert Err = 0
    End If
    Exit Sub
 
FilterTextError3:
    Close nOut
FilterTextError2:
    Close nIn
FilterTextError1:
    MErrors.ErrRaise Err
End Sub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s