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

后端 未结 2 1374
猫巷女王i
猫巷女王i 2021-01-25 14:12

I am populating a short dictionary from my basic C program using the following code :

void main () {

FILE *fp;

fp = fopen(\"c:\\\\CTEMP\\\\Dictionary2.txt\", \         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 14:57

    I used the following code :

    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;
    
        }
    

提交回复
热议问题