Replace a line in a file - Read/Write access posible random How do I do this

Posted on 2003-03-18
Medium Priority
Last Modified: 2010-04-07
im looking to replace a line in a file i wrote a funtion to read the config file im useing and look for a string in it then I want to replace that line it finds with the new string how do I do this im relly stuck.. I keep geeting errors like bad mode and file number/name etc...im relly stuck

here is the code I have so far with error checking
and comments notes for me

I also as you can see tryed in the bottom to do it by stream either way is fine with me I just want it to work

Public Function Write_Config(Line_of_Text As String, Look_For As String)
   Dim FileNumber
   Dim strFilNam As String
   Dim TextLine As String
   On Error GoTo ErrorHandler   ' Enable error-handling routine.

   FileNumber = FreeFile   ' Get unused file
   strFilNam = App.Path & "\ircd.conf"

      Open strFilNam For Random As #FileNumber
      'On Error GoTo 0   ' Turn off error trapping.
      'On Error Resume Next   ' Defer error trapping.

      Line Input #FileNumber, TextLine   ' Read line into variable.
      Debug.Print TextLine   ' Print to the Immediate window.

      If IsInString(TextLine, Look_For) Then
         Print #FileNumber, Line_of_Text
      End If
   Loop Until EOF(FileNumber)   ' Loop until end of file.

   Exit Function      ' Exit to avoid handler.
ErrorHandler:              ' Error-handling routine.
   Select Case Err.Number   ' Evaluate error number.
      Case 52 'Bad file name or number
         msg = "Error # " & Str(Err.Number) & " was generated by " _
            & Err.Source & Chr(13) _
            & Err.Description & Chr(13) _
            & "File: " & Chr(13) _
            & strFilNam & Chr(13) _
            & "File Number is " & FileNumber

         MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext
      Case 55   ' "File already open" error.
         Close   ' Close open file.
      Case Else
         Debug.Print Error(Err.Number)   ' Print error to Immediate window.

         msg = "Error # " & Str(Err.Number) & " was generated by " _
            & Err.Source & Chr(13) & Err.Description
         MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext

   End Select
   Resume   ' Resume execution at same line
   ' that caused the error.

   ' #HOut# ********************
   ' #HOut# Programmer Name  : Pern
   ' #HOut# Date             : 3/18/2003
   ' #HOut# Time             : 18:59
   ' #HOut# Comment          :
   ' #HOut# Comment          :
   ' #HOut# Comment          :
   ' #HOut# ********************
   ' #Out#    Dim a, FS As New FileSystemObject, File As String
   ' #Out#    Close
   ' #Out#    File = App.Path & "\ircd.conf"
   ' #Out#    Set a = FS.OpenTextFile(File, ForAppending, False, TristateFalse)
   ' #Out#       Do
   ' #Out#          frmMain.txtPern.Text = a.ReadLine
   ' #Out#          If IsInString(a.ReadLine, Look_For) Then
   ' #Out#             a.WriteLine Line_of_Text
   ' #Out#          Else: a.SkipLine
   ' #Out#          End If
   ' #Out#       Loop Until a.AtEndOfStream <> True
   ' #Out#    a.Close
   ' #HOut# ********************
End Function

thanks in advance to any help provided
Question by:Johnny
  • 2

Accepted Solution

QJohnson earned 60 total points
ID: 8164092
You need to find the point in the file at which the desired text is found.  Then you write to a new file:
(1) all the text before it,
(2) the replacement for the line of interest, and
(3) all the text after it .

If you assume you will always find the string, just open two files at once, one for reading and the other for writing.  When done, kill the file you read and rename the file you wrote to the good name.  Here's some code to get started, borrowed in part from yours.

Public Function Write_Config(Line_of_Text As String, Look_For As String)
  Dim intFileRead  As Integer
  Dim intFileWrite As Integer
  Dim strFileRead  as string
  Dim strFileWrite As String
  Dim strTextLine As String
  Dim strTextToFind  as string
  Dim strReplacementText as string
  Dim sBuffer as string

  On Error GoTo ErrorHandler   ' Enable error-handling routine.

  intFileRead = FreeFile   ' Get unused file
  strFileRead = App.Path & "\ircd.conf"

'    note we are re-locating the file open statement
'    having it INSIDE the loop meant it was attempting Open after just reading the first line.  Also we open it for Input rather than Random so we can use sequential processing

  Open strFileRead For Input As #intFileRead
'     now the file to be written
  intFileWrite = FreeFile
  strFileWrite = App.Path & "\temp.txt"
  Open strFileWrite for output as #intFileWrite

     Line Input #FileNumber, sBuffer

     If InStr(sBuffer, strTextToFind) > 0 Then
        '  code build replacement line by
        '  (1) getting text to left of found text
        '   not difficult, but too tedious to show here
           (2) inserting Replacement text
           (3) adding text to right of found text
        '  we just need to write the current line into the new file
        Print #intFileWrite, sBuffer & vbcrlf
     End If   ' did we find the string we looked for?


  Close      '  closes them both since no number is given

  Kill strFileRead
  Name strFileWrite As strFileRead

You could probably make this a bit faster by using a flag to track whether or not the string had been found so that you could stop doing the instr() search unnecessarily.  

Author Comment

ID: 8166818
I was able to find an example on exchange (as i was browsing the answers) and moded it to fit my needs...

I thank you for your help in this matter..and the nice explination...
i will award you your points for it..as you did provide a solution and helped...

i have alot of progrmming questions so please look for more from me my next ones about treeview and nodes..

ill post the link here at the bottom for it.

heres what i did to solve the above problem with te search and replace lines... made it a function so i can replace anything i want in the config file..

Public Function Write_Config(Line_of_Text As String, Look_For As String)
   On Error GoTo UpdateErr
   Dim strFile As String
   Dim strTmpFile As String
   Dim strLine As String
   strFile = App.Path & "\ircd.conf"
   strTmpFile = App.Path & "\temp_ircd.conf"

   If (Dir(strTmpFile) <> "") Then ' tmp file exist
       Kill strTmpFile ' delete the file
   End If
   Open strFile For Input As #1
   Open strTmpFile For Output As #2
   ' copy until the line you want
   Do While (Not EOF(1))
       Input #1, strLine
       If IsInString(strLine, Look_For) Then
           Exit Do
       End If
       Print #2, strLine
   ' write the changed line
   Print #2, Line_of_Text
   ' now write the rest of the file
   Do While (Not EOF(1))
       Input #1, strLine
       Print #2, strLine
   ' close open files
   Close #2
   Close #1
   If (Dir(strTmpFile) <> "") Then ' tmp file exist
       Kill strFile ' delete the original file
       ' rename the tmp file as original file
       Name strTmpFile As strFile
   End If

   Exit Function

   MsgBox "Error updating the file." & vbCrLf & Err.Number & ": " & Err.Description
   Reset ' close any open files
   On Error GoTo 0
End Function

Again thanks for your help QJohnson

heres the link for the next problem i have. with treeview and nodes.



Author Comment

ID: 8166849
Thanks again..i didnt grade the answer as A: Excellent!!!  as you did not completely give full code..altho i do belive alowing one to figure out th answer in some cases..i really want full code for answers.

you had no way of knowing this and i did not define this befor hand so i didnt deduct anything from awarding...

thanks alot fo the prompt and great answer..

Johnny aka Pern

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction While answering a recent question (http://www.experts-exchange.com/Q_27402310.html) in the VB classic zone, I wrote some VB code in the (Office) VBA environment, rather than fire up my older PC.  I didn't post completely correct code o…
This article describes how to use a set of graphical playing cards to create a Draw Poker game in Excel or VB6.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question