2

Lets say I have a text file with the following data

Username

User ID

Details

suppose, I want to insert a new line "User screenname" inbetween "User ID" and "Details". How should I do this ? Is it possible to insert string at a specific line ? since these have a variable string length for different users, i think its not possible to use seekToFileOffsetand update the file. please help me out.

Thanks

Mith
  • 150
  • 2
  • 11

1 Answers1

6

The only way to do this is to read the file into memory, modify the internal representation of the data, and write it back out.

There are some variations on this process, but in short; files are not like real paper and ink documents: You can't insert content into the middle of a file, only replace what is already there.

Edit: To clarify, you can only grow a file at the end; not in the middle.

Williham Totland
  • 28,471
  • 6
  • 52
  • 68
  • So files ARE like real paper and ink. – flopr Oct 17 '16 at 16:49
  • @flopr Who knew, right? In truth, there truth isn't _entirely_ so simple, and by hacking about with the file system, sparse files, and precise block alignment, you probably could insert data into the middle of files, but frankly, I wouldn't recommend it. – Williham Totland Oct 17 '16 at 16:51
  • 1
    @flopr Oh, hah, I misread. How they differ from paper and ink in this case, is that if you have a multi-letter document of some description, you can insert a sheet in the middle, or remove one, leaving the stack shorter or taller; which you can't (asterisk) do with a computer file (on most file systems under sane conditions). – Williham Totland Oct 17 '16 at 17:10
  • This bugged me for years. I could not find a definitive answer (until now). I kept thinking that it's more lower level code and I just did not find how to do it. Finally can put this to rest. – bauerMusic Apr 14 '18 at 11:31