C 中的文件处理 - 从文本文件的列表中删除特定单词

File Handling in C - Removing specific words from a list in text file

我正在使用以下代码从我的基本 C 程序中填充一个简短的字典:

void main () {

FILE *fp;

fp = fopen("c:\CTEMP\Dictionary2.txt", "w+"); 

fprintf(fp, Word to Dictionary");

不过,我也希望删除某些我不想再出现在字典中的词。我做了一些研究,我知道

" 您不能从文件中删除内容并将剩余内容向下移动。您只能追加、截断或覆盖。

您最好的选择是将文件读入内存,在内存中处理它,然后将其写回磁盘

如何创建一个没有我要删除的单词的新文件?

谢谢

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

如果您需要进行的操作要复杂得多,那么您实际上可以 "read it into memory" 使用 mmap(),但这是一种更高级的技术;您需要将文件视为没有零终止符的字节数组,并且有很多方法可以搞砸它。

我使用了以下代码:

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;

    }