我想从文件中删除一行,当前我正在循环遍历oldTodoFile
中的每一行,如果lineNumber
不等于todoNumber
,则将它添加到一个新文件(todoFile
)。它似乎并不是一种删除线条的好方法,还有更好的方法来删除线条吗?更好的方式来删除文件中的一行?
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);
非常相似:http://stackoverflow.com/questions/1151713/delete-a-line-from-a-file-in-c-language – 2011-04-19 21:52:36
没有出现在搜索:http:// stackoverflow。 COM /搜索?q =更好的方式+ +至+删除+ A +线+在+ A +文件%3F – errorhandler 2011-04-19 21:54:25