-1

I am stapting working with file in C. The task is to delete difinite line from file.

I've created void del (); function which should delete difinite line from file. Program is runnig, but don't deleting a line.

Can you correct my mistake please?

 void del ()
    {
    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(filename, "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.txt", "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(filename);
    //rename the file replica.c to original name
    rename("replica.txt", filename);
    printf ("Press ENTER to continue");
    _getch ();
    printf("\n The contents of file after being modified are as follows:\n");
    fileptr1 = fopen(filename, "r");
    ch = getc(fileptr1);
    while (ch != EOF)
    {
        printf("%c", ch);
        ch = getc(fileptr1);
    }

    fclose(fileptr1);
    sub();
};

1 Answers1

3
char ch;

This is wrong. getc and friends return an int. This is not something you are free to shrug off and continue on your merry way.

ch = getc(fileptr1);
while (ch != EOF)
 {
     ch = getc(fileptr1);

You are losing the very first character of the file for ever this way. Find any example of a getc/fgetc/getchar based loop in any introductory C book.

if (ch == '\n')
    temp++;
if (temp != delete_line)
{
    //copy all lines in file replica.c
    putc(ch, fileptr2);
}

If you try to delete the first line, you replace it with an empty line instead. Use your debugger to verify that. Determine which newline character you are skipping when you are deleting line number N. Think what you have to do to fix that.

Community
  • 1
  • 1
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • @EricPostpischil: If `fopen()` failed, it's quite possible for `getc()` to crash because it was given a null `FILE *` and it wasn't expecting it. – Jonathan Leffler May 14 '17 at 20:42
  • @JonathanLeffler: Yes. Looking again, that sequence is intended to display the file contents for the user, for them to look at while selecting a line to delete. – Eric Postpischil May 14 '17 at 23:16