如何从文本文件中删除?

Jos*_*eri 2 c file-handling

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


Daw*_*ime 6

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

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;

    }
Run Code Online (Sandbox Code Playgroud)