Page 1 of 1

Insert text to textfile

Posted: Fri Sep 19, 2008 11:14 am
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............

Posted: Fri Sep 19, 2008 7:52 pm
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

Posted: Fri Sep 19, 2008 8:03 pm
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.

Posted: Fri Sep 19, 2008 8:03 pm
by Rescator
damn, eJan beat me to it, with source and everything :P