• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 120
  • Last Modified:

Reading from & writing into text file

Can anyone tell me how to open a text file both in read & write modes. I need to scan line by line in the text file & need to make changes in each line then write back to the same text file.
Preferrably using open # statement.
  • 4
1 Solution
You can't have a ordinary text file open in both read&write. What you can do is open the textfile, open a temporary file and for each line read the data from the textfile, do any changes if neccessary and then save it to the temporary file. When all lines are done, you close both files. Then you do the Kill statement on the textfile and use the Name statement to rename the temporary file to whatever the textfile was called.
Here's the code:

  Dim Rad As String
  Dim SourceFile As String
  Dim SourceFileNr As Integer
  Dim TempFile As String
  Dim TempFileNr As Integer
  SourceFile = "D:\A.txt"
  TempFile = "C:\A.txt"
  SourceFileNr = FreeFile
  Open SourceFile For Input As #SourceFileNr
  TempFileNr = FreeFile
  Open TempFile For Output As #TempFileNr
  Do Until EOF(SourceFileNr)
    Line Input #SourceFileNr, Rad
    'Do any changes on the Rad string
    Print #TempFileNr, Rad
  Close #TempFileNr
  Close #SourceFileNr
  Kill SourceFile
  Name TempFile As SourceFile
TempFile = SourceFile & ".bak"

is probably a better solution
kbalarajuAuthor Commented:
Can we open a text file having size of more than 100MB using open & work with it! Do we have any size limitaions while working with them???

The Seek command which is used to get the current position within a file is limited to 2Gb, so any size up to 2Gb should work fine.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now