How to delete a record from a text file?

445 views Asked by At

How do you delete a record (that is in array struct) from a text file? My code works but it deletes other records too. May I know whats wrong with my code? Here's what it looks like:

{           
    zfp = fopen("note.txt", "wb+");
    if (fp == NULL)
    {
          printf("| File can not be opened.\n");
          exit(1);
    }
    for(int k = 0; k < len; k++)
    {
        if(k == s)
        {
            strcpy(notes[s].title, "\0");
            notes[s].day = 0;
            notes[s].month = 0;
            notes[s].year = 0;
        }
    }
    fwrite(&note, sizeof(note), 1, fp);
    fclose(fp);
}

By the way, before that part, I have a code that asks for the event number that you want to delete. The array index starts at 0 and the event number starts at 1. So the data/record associated with that event number would be s = eventnumber - 1 to match with the index of the arrays.

1

There are 1 answers

0
Barmar On

Write the records one at a time rather than writing the whole array. Then you can simply skip the one that you want to delete.

{           
    zfp = fopen("note.txt", "wb");
    if (fp == NULL)
    {
          printf("| File can not be opened.\n");
          exit(1);
    }
    for(int k = 0; k < len; k++)
    {
        if(k != s)
        {
            write(&notes[k], sizeof(notes[k]), 1, fp);
        }
    }
    fclose(fp);
}