gpt4 book ai didi

c - 删除文件中一行的更好方法?

转载 作者:太空宇宙 更新时间:2023-11-04 06:42:43 25 4
gpt4 key购买 nike

我想从文件中删除一行,目前我正在遍历 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);

最佳答案

文件只是一系列字节。如果要删除一行,则必须将该行之后的所有内容移回原位。我认为您正在做的很好,但您也可以从要删除的行开始覆盖现有文件。

为此,您需要两个指向文件的文件描述符。当您从第二个阅读时,您会写到第一个。

完成后,您可以截断文件以去除末尾的额外数据。

关于c - 删除文件中一行的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5723147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com