I want to remove a line from a file, the currently I'm looping over each line in oldTodoFile and if the lineNumber doesn't equal todoNumber then add it to a new file(todoFile). It doesn't seem that is a good way of deleting a line, is there a better way of removing a line?

3 Answers
3

A file is just a series of bytes. If you want to remove a line, you will have to shift anything after that line back. I think what you are doing is just fine, but you could also overwrite the file in place starting at the line you are removing.

To do this, you would need two file descriptors pointing into the file. As you are reading from the second one, you would write to the first one.

When you are done, you can truncate the file to get rid of the extra data at the end.

If your OS supports memory mapped files, you could memeory map the file and then use memmove() to move the data. It may or may not be more efficient, but the resulting code may be simpler to implement, maintain and debug.

It is not necessarily a "better" way, but it is something to consider.