如何从文本文件中删除?

大家好我有一个文本文件,称为dictionary.txt。 基本上我正在做两个选项的菜单,1。在字典中添加新单词和2.从字典中删除单词。 现在我设法做菜单并添加新单词。 但是,我无法从文件中删除。 我希望当用户输入例如“runners”时,在dictionary.txt中搜索该单词并将其删除。 告诉你我在学校尚未涉及的所有内容,但我在这里寻找一些想法,以便我可以继续完成任务。 我已经尝试了一些东西,但正如我已经告诉过你的那样,我还没有覆盖它,所以我不知道如何实际做到这一点。 我感谢所有的帮助。 以下是我的计划。


  • 你打开两个文件:你有一个(用于阅读)和一个新文件(用于写作)。
  • 循环遍历第一个文件依次读取每一行。
  • 您将每行的内容与您需要删除的单词进行比较。
  • 如果该行与任何删除单词都不匹配,则将其写入新文件。

Josuel,取自Richard Urwin之前回答的问题

您可以使用以下代码:

 #include  int main() { FILE *fileptr1, *fileptr2; char filename[40]; char ch; int delete_line, temp = 1; printf("Enter file name: "); scanf("%s", filename); //open file in read mode fileptr1 = fopen("c:\\CTEMP\\Dictionary.txt", "r"); ch = getc(fileptr1); while (ch != EOF) { printf("%c", ch); ch = getc(fileptr1); } //rewind rewind(fileptr1); printf(" \n Enter line number of the line to be deleted:"); scanf("%d", &delete_line); //open new file in write mode fileptr2 = fopen("replica.c", "w"); ch = getc(fileptr1); while (ch != EOF) { ch = getc(fileptr1); if (ch == '\n') { temp++; } //except the line to be deleted if (temp != delete_line) { //copy all lines in file replica.c putc(ch, fileptr2); } } fclose(fileptr1); fclose(fileptr2); remove("c:\\CTEMP\\Dictionary.txt"); //rename the file replica.c to original name rename("replica.c", "c:\\CTEMP\\Dictionary.txt"); printf("\n The contents of file after being modified are as follows:\n"); fileptr1 = fopen("c:\\CTEMP\\Dictionary.txt", "r"); ch = getc(fileptr1); while (ch != EOF) { printf("%c", ch); ch = getc(fileptr1); } fclose(fileptr1); scanf_s("%d"); return 0; } 

无法从文件中删除某些内容。 文件系统不支持它。

多数民众赞成如何修改文件的内容:

  • 删除整个文件内容(无论何时打开文件进行写入,默认情况下都会发生)
  • 删除文件本身
  • 重写文件的某些部分,用相同的字节数替换几个字节
  • 追加到文件的末尾

因此,要删除单词,您应该将整个文件读取到内存中,删除单词,然后重写它,或者用空格(或任何其他字符)替换单词。

您可以以二进制模式打开文件,然后将内容加载到字符串或字符串数​​组,然后对字符串执行搜索/删除/编辑,然后清除文件的内容,最后将新内容写入文件。