Reputation: 1
I'm trying to create a program where I can write a string to the end of a certain line in a text file.
For example, this is the text file with just a bunch of random numbers:
12 23
53 23
Now what if I had a program that adds another two-digit number to the end of the first line (or any specified line), keeping in mind that the line will keep expanding if I kept running the program over again.
So after running the program, the text file would look something like this:
12 23 34
53 23
What are some ways to solve this?
Upvotes: 0
Views: 1114
Reputation: 149175
You should never try to edit a text file in place. The most common way is to write the edited file in a temporary location, and at the end rename it to the old name (after removing the original file).
The other way is (provided the file is small enough) to load everything in memory and to rewrite the file from the beginning. But never do that on sensitive files because if your program (or your computer or electric power) crashes in the middle, you file will be definitively lost.
Upvotes: 0
Reputation: 67345
If I understand the question, this is not possible. The problem is that if you make one line longer, it would overwrite the next line. You seem to be expecting the following lines to shift down to make room but that's not how it works.
Unless your file is huge, the best approach is to load the file into memory, modify the data in memory, and then create a new file to save the results. (You can save to the same file if needed.)
Other algorithms involve using blocks of a fixed size, having a linked list in your file, but it sounds like you want you file to be normal text and so those likely wouldn't work.
Upvotes: 2