How to delete lines or character from file?

I searched on Google for hours and was only able to find this and even this doesn't say how to do the operation.
Technically, copying everything from file to string, editing and writing all over again on the same file works but, I felt it would be inefficient and not the right procedure for this.
So how to do this like directly on the file itself?

Unless you have a file that's a couple of 100s of megabytes or more, just do that.
Only at that scale does it become worth it to deploy other (possibly OS-specific) means of altering files.

Is it that complex? Like how does the editors do it? No wonder I was struggling to find some answers on google

Updating files without the possibility of data corruption can be somewhat finicky regardless of the programming language used. That's a direct consequence of how file systems work.

So, in order to keep things simple, it's better to just read the file to string, perform a seek into the string, and then edit that.

Then, for a file named "myfile.txt", write the string to a new file named something like "", and once that is done, rename the file to the name of the original "myfile.txt". Doing this prevents half-written files in the event of e.g. a power failure. This is because the actual writing is O(n) in the length of the file, whereas renaming is pretty much O(1) and thus much harder to corrupt.


Pretty much all text editors will just overwrite the full contents of the file.

If you want to edit the file directly without rewriting all of it, the way is to open it in write mode without truncate, then use the Seek trait to move the cursor to the part you wish to overwrite, and then overwrite that part. Note that this method is only really efficient if you wanted to replace some part of the file with new data of the same length. To delete a line, you must copy all bytes after that line backwards to remove the hole. Files behave like an array Vec<u8>, and removal in the middle is expensive for this kind of data structure.

Removal at the end of the file is much easier and can be done with File::set_len.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.