Insert text to textfile

Just starting out? Need help? Post your questions and find answers here.
Jimboi
User
User
Posts: 19
Joined: Fri Jul 25, 2008 10:41 am
Location: Malaysia

Insert text to textfile

Post by Jimboi »

This is newbie question..any comments will not get paid! :wink:
how do you people insert one line text to text file that already contain some text without load all contain to variable and insert whatever text to variable then write back to textfile like i always do.... :?

example...
original textfile

this is line 1............
this is line 2............
this is line 3............
this is line 4............
this is line 5............

,-----------------------------
after insert

this is line 1............
this is line 2............
this is line 3............
this is new line......... <---------new line ad here
this is line 4............
this is line 5............
eJan
Enthusiast
Enthusiast
Posts: 366
Joined: Sun May 21, 2006 11:22 pm
Location: Sankt Veit am Flaum

Post by eJan »

My method using LinkedList:
1. Read 'original.txt' and store its strings into LinkedList (memory), close file
2. Insert new string - element after 3rd one
3. Create new file (replace existing one, now you have content stored into memory)
4. Write LinkedList content into new file (original.txt)
Offcourse this can be done in different/simple way, but i like LinkedLists()

Code: Select all

file.s = "original.txt"

NewList text.s()

If ReadFile(0, file)

  While Eof(0) = 0
    AddElement(text())
    text() = ReadString(0)
  Wend
  
  CloseFile(0)

  ResetList(text())
  For i = 0 To CountList(text())
    NextElement(text())
    If i = 2
      AddElement(text())
      text() = "new line ad here"
    EndIf
  Next

  CreateFile(0, file)
  ResetList(text())
  While NextElement(text())
    ;Debug text()
    WriteStringN(0, text())
  Wend
  CloseFile(0)

EndIf
User avatar
Rescator
Addict
Addict
Posts: 1769
Joined: Sat Feb 19, 2005 5:05 pm
Location: Norway

Post by Rescator »

Use ReadString() and a string list, it should be easy to remove/add/insert/replace a line then using the list functions.

You may also wish to set a larger file buffer for the file before you start the reading loop to speed things up some more.

Writing back to disk is as easy as doing a ForEach on the list and using WriteStringN()

Only downside is that very large text files will need a large amount of memory.

There are other ways to do this but, for a beginner or for not really huge files this is a good starting point.
User avatar
Rescator
Addict
Addict
Posts: 1769
Joined: Sat Feb 19, 2005 5:05 pm
Location: Norway

Post by Rescator »

damn, eJan beat me to it, with source and everything :P
Post Reply