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");
r开发者_运维技巧ename("./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.
Nope, that's the way to do it. There's no way to delete data from the middle of a file.
You might want to fix your code in the event of an error, it still tries to do the delete/rename 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.
精彩评论