C:更新文件中的多个记录

C:更新文件中的多个记录,c,file-io,C,File Io,这是以下内容的后续内容: 函数do_update()根据条件更新文件中的多条记录。但是,该功能不起作用: 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("c

这是以下内容的后续内容:

函数
do_update()
根据条件更新文件中的多条记录。但是,该功能不起作用:

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);
}
fwrite
调用没有更改文件上的记录。我检查了这个函数的返回值,首先匹配它返回
1
,如果有其他匹配,它返回
0
。但是,当我再次打开文件时,没有修改任何记录


有人能帮我吗?

你可以试试这个。因为这是一个do-while循环,所以在循环之前不需要fread。do将始终执行该块一次。您需要声明
long fileposition。在第一个fseek中,-sizeof应该将文件位置移回刚刚读取并允许您写入的结构的开头。第二个fseek应该让您重新阅读

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

工作起来很有魅力。谢谢