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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inserting text into a Text File

Status
Not open for further replies.

StevenK

Programmer
Jan 5, 2001
1,294
GB
I have a Delphi application that is able to read strings from a Text (or 'csv') file and similarly append strings to the end of the file.
Is there a method of inserting Strings into a specific point in this text file, i.e. read through 10 lines (of a 100 line file) and then insert a String as required ?
Thanks in advance
Steve
 
The easiest way I can think of to do that would be to do a TStringlist.LoadFromFile and insert your strings, and then do a TStringlist.SaveToFile. If the files are huge though you might need to read from the first file one line at a time, write to a second file until you get to the insertion point, insert the new lines and then read the remainder of the file copying it over to the second file. If that makes sense. :) TealWren
 
Thanks very much for the suggestion - looks like I'll be having to follow this scheme.
Is there no direct method of forcing a line of text (String) to be inserted at a given point in the text file if I have read the appropriate number of lines such that I am sitting at the correct insertion point ?
Thanks again
Steve
 
As far as I know, using MSWindows you can't do that with any file. (That's not to say you can do it with any other OS, I'm just not sure on others. :) )

It would involve moving the end of the physical file down a bit to add something to the middle - and I think that's just not supported the way file storage is done. I think Delphi is restricted by the operating system in this case.

TealWren
 
Hello StevenK
I aggree with Tealwrens first suggestion load the file into a stringlist do the manipulations and re-save it.
You could have a look at the 'filesize' and 'filepos' functions and the 'seek' procedure, you might find something useful in these but I wouldnt call it an easy way!

Steve.
 
Thanks for the suggestions, I've settled on the idea that I load the first 'x' lines from the file into a Memo, insert my additional line(s) and then feed the remaining lines from the file, then allowing the lines to be saved from the memo to the file again.
The files are currently a small size so this solution works OK at present.
Thanks again.
Steve
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top