Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

WHAT IS THE BEST WAY TO CHANGE TEXT IN THE MIDDLE OF A TEXT FILE? 3

Status
Not open for further replies.

faxpay

Programmer
Nov 30, 2004
119
0
0
US
I have an ascii file in a small app that I want to open and delete text and add different text in the middle of the file. I tried using the fso but found out it will not let you work in the middle of a file.

Tom
faxpay
 
If you know the start location of the data you want to change AND the new data is the same length as the old data:

OPEN <path to file> FOR OUTPUT LOCK WRITE AS <file handle>

Then use SEEK, GET and PUT to update the file.


If you don't know where you want to update from or the data is a different length:

The simpiliest thing to do would be to read the entire file into memory, make your change and then put it all back.

 
I tried random access and could not make work. Then tried binary and still no good. I am trying to pull just the first 10 characters from the first line of the text file to edit them and then put back. The code is as follows:

FileNo = FreeFile

Open "c:\BANK OF AMERICA DIRECT DEPOSIT FILE FOR TRANSMISSION\HTTP ACH PAYRLR CAFR1031" _
For Binary As FileNo

RecNo = 10

Get #FileNo, RecNo, Lineout

Lineout is the string variable.
I get no errors but the string Lineout keeps coming back empty.

faxpay, Tom
 

What about the simple, low-tech approach:

I have a text file (TextFile.txt) that looks like this:
Code:
This is first line
of text
[blue]change this[/blue]
last line
that I want to change the blue line of text.
Code:
Dim strTextLine As String

Open App.Path & "\TextFile.txt" For Input As #1
Open App.Path & "\TextFileOut.txt" For Output As #2

Do While Not EOF(1)
    Line Input #1, strTextLine
    If strTextLine = [blue]"change this"[/blue] Then
        Print #2, [blue]"to that"[/blue]
    Else
        Print #2, strTextLine
    End If
Loop

Close #2
Close #1

Than it is just Delete the original file and Rename new file. Done.

Have fun.

---- Andy
 

Using the input statement as below will return the first ten characters in your file.
Code:
Dim FirstTenStr as string


FileNo = FreeFile

sFile = "c:\BANK OF AMERICA DIRECT DEPOSIT FILE FOR TRANSMISSION\HTTP ACH PAYRLR CAFR1031"

Open sFile For Input As FileNo 
	FirstTenStr = Input(10, FileNo)
Close FileNo
 
<and add different text in the middle of the file

<I am trying to pull just the first 10 characters from the first line of the text file to edit them and then put back

Sounds like two different things to me...
 
BobRhodes,

Your right. I am contradicting myself. What I truely want to do in the first line of the text file is replace a space with a "1". That's all. If I just new how to randomly access, or however, text then I could make changes to the string variable and put it back. Sound right?

faxpay, Tom
 
To test this example start a new project and place a plain text file named "my.txt" containing your example data in the directory of the test project.

Also add a commandbutton and a textbox.
Then paste this code

Code:
Option Explicit

Public Sub ChangeFileText()
    Dim FirstLineStr As String
    Dim strTextLine As String
    Dim sFile As String
    Dim TempFile As String
    Dim NewFirstString As String
    Dim NewLineEntered As Boolean
    
    sFile = App.Path & "\my.txt"
    TempFile = App.Path & "\temp.txt"
    
    NewLineEntered = False
    
    Open sFile For Input As #1
        Line Input #1, FirstLineStr
    Close #1
    
    'comment this out for real thing this is
    'just to quickly display string changes
    Text1.Text = ChangeString(FirstLineStr, " ", "1")
    
    NewFirstString = ChangeString(FirstLineStr, " ", "1")
    'now using Andrzejek method rewrite the file
    Open sFile For Input As #1
    Open TempFile For Append As #2
    Do While Not EOF(1)
        Line Input #1, strTextLine
        If NewLineEntered = False Then
            Print #2, NewFirstString
            NewLineEntered = True
        Else
            Print #2, strTextLine
        End If
    Loop
    
    Close #1
    Close #2
    
    'and lastly rename and remove temp file
    Kill sFile
    Name TempFile As sFile
End Sub

Private Sub Command1_Click()
    ChangeFileText
End Sub


Public Function ChangeString(StrToChange As String, ChartoFind As String, ReplacementChar As String) As String
    'the instr function will find the first occurance of ChartoFind
    'if u need to replace all occurances use the commented out replace method
    Dim foundLoc As Long
    
    foundLoc = InStr(StrToChange, ChartoFind)
    If foundLoc >= 0 Then
        ChangeString = Mid(StrToChange, 1, foundLoc - 1) & ReplacementChar & Mid(StrToChange, foundLoc + 1, Len(StrToChange) - foundLoc + 1)
    Else
    End If
    
    'method to replace all spaces with ones
    'ChangeString = Replace(StrToChange, ChartoFind, ReplacementChar)
End Function

Private Sub Form_Load()
    Command1.Caption = "Change File"
    Text1.Text = ""
End Sub

 
this line: If foundLoc >= 0 Then
should be this: If foundLoc > 0 Then

Also is there a reason all this information couldnt be stored in one random access file?

I am only asking because you could then pull the information from one file and manipulate only the data that requires manipulation.
 
Erm ... why would anyone want to rewrite the entire file if we are making a single character replacement?

' Replaces first instance of a character in the first line of a file with another character
Public Sub Example(strFile As String, strFindChar As String, strReplaceChar As String)
Dim hFile As Long
Dim aLine As String

hFile = FreeFile
Open strFile For Input As hFile
Input #hFile, aLine
Close hFile

Open strFile For Binary As hFile
Put hFile, InStr(aLine, strFindChar), strReplaceChar
Close hFile
End Sub

 
strongm

Thank You. I knew there must be an easier way. That worked just fine except I had trouble working that instr function into the put statement. Ended up having to use separate line to return position to variable.

Thanks again

Excuse my ignorence but what is thar MIS after your name.

faxpay, Tom
 
Management Information Systems. You may be aware of this, but the Instr function returns the offest of the found character in the input string as an integer.
 
BobRhodes,

Not sure what you mean by: "Instr function returns the offest of the found character"

Returns the position, No? What is meant by offset?

faxpay,Tom
 
<What is meant by offset?

Um, position. [lol]

Meaning how far you are "set off" from the initial position.

I mentioned this because I can't see why strongm's code doesn't work for you as given. Knowing his posts from the past, I can say with a strong degree of certainty that it worked for him! Would you like to post your version so we might have a look at why?

Bob
 
ok Bob,

Here it is:

Private Sub Cmd1_Click()
Dim fso As New FileSystemObject
Dim FileNo As Integer
Dim Lineout As String
Dim RecNo As Integer
Dim Position As Long
Dim Substitute As String
Dim Find As String
Find = " 204696825"
Substitute = "1204696825"



On Error GoTo HandleErr

Me.Lbl1.Visible = True
Form1.Refresh
'Delete old ACH file on TOM computer.
fso.DeleteFile "c:\BANK OF AMERICA DIRECT DEPOSIT FILE FOR TRANSMISSION\*.*", True
'Copy ACH file from Nicki computer to TOM computer and change name of file.
fso.CopyFile "\\Nicki\NICKI C\\payroll\pyrlcur\ach00003", "c:\BANK OF AMERICA DIRECT DEPOSIT FILE FOR TRANSMISSION\HTTP ACH PAYRLR CAFR1031", True
'Find next free file number.
FileNo = FreeFile
'Open ACH file on TOM computer and copy first line of ACH file into string variable.
Open "c:\BANK OF AMERICA DIRECT DEPOSIT FILE FOR TRANSMISSION\HTTP ACH PAYRLR CAFR1031" _
For Input As FileNo
Input #FileNo, Lineout
Close FileNo
'Find position of beginning of replacement(character count from left of single
'line in variable.
Position = InStr(Lineout, Find)
'Use above character position to overwrite with replacement text.
Open "c:\BANK OF AMERICA DIRECT DEPOSIT FILE FOR TRANSMISSION\HTTP ACH PAYRLR CAFR1031" _
For Binary As FileNo
Put #FileNo, Position, Substitute
Close FileNo

I didn't use any string variables for the paths as for me its easier to see what is going on. Notice I had to get that offset(position) with a single line outside the instr function.

faxpay, Tom
 
Bob,
Sorry, "meant outside the put statement"
faxpay, Tom
 
The point is that there is absolutely no reason why you shouldn't be able to use instr in the put line. Perhaps you could show us your version of the non-working code.
 
Thank you strongm, that's exactly what I'm interested in.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top