Guillermo Guardastagno
Guillermo Guardastagno

Reputation: 557

C: Update multiple records on file

This is a follow-up from this: C: One pointer for reading and one pointer for updating the same file.

The function do_update() seeks to update multiple records on a file depending on a condition. However, that function is not working:

void do_update(char name[]) {
    FILE *my_file;
    int records_read;
    int records_written;
    struct my_struct an_struct;
    struct my_struct empty_struct = {"", -1};

    my_file = fopen("consulta.dat", "rb+");

    records_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file); 
    while (records_read == 1) {
        if(strcmp(name, an_struct.name) == 0){
            records_written = fwrite(&empty_struct, sizeof(struct my_struct),
                1, my_file);
            //At first match this returns one, other matches return 0.
            //It never updates the file
        }
        records_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file); 
    }

    fclose(my_file);
}

The fwrite call is not changing the records on the file. I was checking the return value of this function and at first match it returns 1, if there are another matches it returns 0. However, when I open the file again no record was modified.

Anyone can give me a hand on this?

Upvotes: 0

Views: 187

Answers (1)

user3121023
user3121023

Reputation: 8286

You can try this. As this is a do-while loop you do not need the fread before the loop. do will always execute the block once. You will need to declare long fileposition;. In the first fseek, the -sizeof should move the file position back to the beginning of the structure just read and allow you to write. The second fseek should let you read again.

do {
    records_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file); 
    if(strcmp(name, an_struct.name) == 0){
        fseek ( my_file, -sizeof(struct my_struct), SEEK_CUR);
        records_written = fwrite(&empty_struct, sizeof(struct my_struct),
            1, my_file);
        fileposition = ftell ( my_file);
        fseek ( my_file, fileposition, SEEK_SET);
    }
} while (records_read == 1);

Upvotes: 1

Related Questions