【问题标题】:File Handling in C - Removing specific words from a list in text fileC 中的文件处理 - 从文本文件的列表中删除特定单词
【发布时间】:2017-05-23 14:44:15
【问题描述】:

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

void main () {

FILE *fp;

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

fprintf(fp, Word to Dictionary");

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

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

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

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

谢谢

【问题讨论】:

  • 逐字读取源文件,对于您想要的每个单词,将其写入输出。
  • "您最好的选择是将文件读入内存,在内存中处理,然后将其写回磁盘。" “过程”部分根本就是不在文件中写入您不想要的数据。
  • @Jean-BaptisteYunès 和 @Some 程序员老兄 感谢您的贡献。

标签: c file-handling


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

如果您需要执行的操作要复杂得多,那么您可以使用 mmap() 将其“读入内存”,但这是一种更高级的技术;您需要将文件视为没有零终止符的字节数组,并且有很多方法可以解决这个问题。

【讨论】:

  • 感谢@Richard Urwin 的意见。我的操作没有那么复杂,所以我会去还是你的第一种方法。
  • 完成后,您将得到两个文件:旧文件和新文件。您可能想用新文件替换旧文件,并且有一种不明显的模式可以做到这一点:关闭两个文件后,首先重命名旧文件。然后将新文件重命名为原名,然后删除旧文件。如果您不这样做并且出现问题,您最终可能会丢失所有数据。
  • 嗨,理查德,你介意我问你几个关于你刚才在聊天中所说的问题吗?
【解决方案2】:

我使用了以下代码:

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;

    }

【讨论】:

    猜你喜欢
    • 2017-03-31
    • 2021-05-16
    • 1970-01-01
    • 2018-10-22
    • 2017-06-21
    • 2013-10-06
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    相关资源
    最近更新 更多