如何从文本文件中删除?

How can I delete from a text file?

大家好,我有一个名为 dictionary.txt 的文本文件。基本上我正在做一个有两个选择的菜单,1. 向字典添加新词和 2. 从字典中删除词。现在我设法做了菜单并添加了新词。但是,我坚持从文件中删除。我希望当用户输入例如 "runners" 时,会在 dictionary.txt 中搜索该词并将其删除。告诉你我在学校还没有涵盖的所有内容,但我正在这里寻找一些想法,以便我可以继续完成任务。我已经尝试了一些事情,但正如我已经告诉过你的那样,我还没有介绍它,所以我不知道如何实际去做。我感谢所有的帮助。下面是我的程序。


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

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

Josuel,摘自我之前由 Richard Urwin 回答的问题

您可以使用以下代码:

#include <stdio.h>

    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;

    }

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

这就是修改文件内容的方法:

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

所以要删除一个词,您应该将整个文件读入内存,删除该词,然后重写,或者用空格(或任何其他字符)替换该词。