C语言中的文件处理 - 从文本文件

时间:2017-01-09 10:51:06

标签: c file-handling

我使用以下代码从我的基本C程序填充一个短词典:

void main () {

FILE *fp;

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

fprintf(fp, Word to Dictionary");

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

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

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

如何在没有“我想删除”字样的情况下创建新文件?

由于

2 个答案:

答案 0 :(得分:4)

  • 你打开两个文件:你有一个文件(用于阅读)和一个新文件(用于 写入)。
  • 循环浏览第一个文件,依次读取每一行。
  • 您可以将每行的内容与您需要的字词进行比较 删除。
  • 如果该行与任何删除词都不匹配,那么 你把它写到新文件。

如果您需要做的操作要复杂得多,那么您可以直接将其读入内存"使用mmap(),但这是一种更高级的技术;你需要将文件视为没有零终止符的字节数组,并且有很多方法可以搞砸了。

答案 1 :(得分:0)

我使用了以下代码:

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;

    }