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

时间:2014-07-07 19:03:34

标签: c file-io

这是后续行动:C: One pointer for reading and one pointer for updating the same file

函数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。但是,当我再次打开文件时,没有修改记录。

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

你可以试试这个。由于这是一个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);