File Input & Output Example (Text File in VB):
Return to List
Private Sub ModifyFile(ByRef PassedFilename As String)
Dim intReadChan As Integer, Incoming_Text As String, ChangeCount As Integer, TotalCount As Integer
intReadChan = FreeFile' Get first open file number (i.e., free channel) Open PassedFilename For Input As intReadChan' Can now refer to input file by this intWriteChan = FreeFile' Get next free channel for output Open "C:\Temp\Test.out" For Output As intWriteChan' A predesignated output file ' Code for reading input file and writing output file TextOld = txtFind.Text' A text string obtained from a textbox (something to test the I/O process) TextNew = txtReplace.Text' The replacement text Unload Me' Can't unload until we've obtained out strings! Do While Not EOF(intReadChan)' A loop to read until end of file -- very similar to PERL Line Input #intReadChan, Incoming_Text
TextPos = InStr(Incoming_Text, TextOld)' The usual string manipulation stuff. If TextPos > 0 Then
LeftSide = Left(Incoming_Text, TextPos - 1)
RightSide = Right(Incoming_Text, Len(Incoming_Text) - (TextPos + Len(TextOld) - 1))
Incoming_Text = LeftSide & TextNew & RightSide
ChangeCount = ChangeCount + 1' Incrementing our counter for the Final Results message End If
Print #intWriteChan, Incoming_Text' Either "Print" or "Write" can be used here -- however, Print is a little faster with no surrounding quotes! Line returns can be suppressed by following the term to be printed with a semi-colon TotalCount = TotalCount + 1' The counter of total lines written Loop
Close intReadChan' Must close opened file Close intWriteChan' Must close opened file MsgBox "There were" & Str(TotalCount) & _
" lines written to the output file " & Chr(34) & _
"C:\Temp\Test.out" & Chr(34) & vbCrLf & _
"and" & Str(ChangeCount) & " changes incorporated.", _
vbInformation + vbOKOnly, _
" Final Results"
End
End Sub