Forum Discussion

mfoster711's avatar
mfoster711
Regular Contributor
10 years ago

Insert into TXT file

I am trying to insert text into a TXT file and having issues.

 

I have a process currently that reads and updates TXT files using ReadLine and WriteLine and it works fine as long as I format the lines to always be exactly the same length.

 

Now, I am trying to create a new process where I need to read through the same TXT, find a specific line, and then insert text at the end of that line. This causes the lines to now be different lengths. When I look at the TXT file afterwards, the new text was inserted but the very next line is missing characters. If I inserted 10 characters on line 5 then line 6 is missing the first 10 characters.

 

Am I trying to do something that is not practical? Here is my code:

 

Set myFile = aqFile.OpenTextFile(FilePath, aqFile.faReadWrite, aqfile.ctANSI, False)
myFile.Cursor = 0
Line = -1
Do While Not myfile.IsEndOfFile
    CurrentLine = myFile.ReadLine
    Line = Line + 1
    If ThisIsTheLineIamLookingFor Then
        CurrentLine = CurrentLine & Trim(NoteValue) 
        Call myFile.SetPosition(Line, 0)
        myFile.WriteLine(CurrentLine)
        Exit Do
    End If
Loop
myFile.Close

 

1 Reply

  • TanyaYatskovska's avatar
    TanyaYatskovska
    SmartBear Alumni (Retired)

    Hi Mark,

     

    Perhaps, you will like using regular expressions. By using them, it's easy to operate with strings.

    For example, it's possible to search some text fragment based on the specified patterns in the entire string, and/or replace some text. Please refer to the Using Regular Expressions in Scripts article containg the description of this approach as well as several samples.