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?
FILE *oldTodoFile;
oldTodoFile = fopen("./todo.txt", "r");
FILE *todoFile;
todoFile = fopen("./todo2.txt", "w");
int lineNumber = 0;
int len;
char line[4096];
if (oldTodoFile != NULL) {
while (fgets(line, sizeof line, oldTodoFile)) {
len = strlen(line);
if (len && (line[len - 1] != '\n')) {} else {
lineNumber++;
if (lineNumber == todoNumber) {
// Do nothing
} else {
fputs(line, todoFile);
}
}
}
} else {
printf("ERROR");
}
remove("./todo.txt");
rename("./todo2.txt", "./todo.txt");
fclose(oldTodoFile);
fclose(todoFile);
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.