I am trying to figure out how to overwrite a single line in a text file for an appointment program I am making. I am having a difficult time with this because I can't figure out how to overwrite a single line. If I could solve this, I could get my delete button (it's GUI) working and my edit button working. Thanks in advance!
Read the file, and as you're reading it, write it out to another one, without writing the line you wish to delete.
Then rename the original file, rename the new file to the original filename, then, if all that was successful,
delete the original file. If it wasn't successful, rename the original file back to the original name.
The short answer is that "overwriting" in a text file is problematic, and for a couple reasons:
1. Often you want to replace 50 characters with 70 characters or 30 characters and you can't make a file simply grow or shrink like that.
2. Your text encoding may have some surprises in store for you. Common encodings like UTF-8 can encode a single character as 1, 2 or three bytes depending on its value, so even if you think you are replacing 50 characters with 50 characters, you may be replacing 80 bytes with 84 bytes.
The solution is to rewrite the entire file. More precisely:
1. create a new file and write to it.
2. delete the old file.
3. rename the new file to take the place of the old file.
edit: too slow!