C:用于读取一指针和用于更新同一文件中的一个指针 [英] C: One pointer for reading and one pointer for updating the same file

查看:183
本文介绍了C:用于读取一指针和用于更新同一文件中的一个指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要建立一个程序,读取每一个记录,并根据该记录信息将更新在同一个文件中的一些其他记录。对于这一点,我想在这种方式:

I need to build a program that reads each record, and according to that record information would update some other records on the same file. For that, I was thinking in this approach:

int main(int argc, char *argv[]) {
    FILE *my_file;
    int files_read;
    struct my_struct an_struct;

    my_file = fopen("myfile.dat", "rb");

    files_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file);
    printf("main->files_read: %d \n", files_read); //This prints one

    while (files_read == 1) {
        do_update();
        files_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file);
        printf("main->files_read: %d \n", files_read); //This prints one
    }

    fclose(archivo_paises);
    return 0;
}

在主函数我在看文件的内容,每一个我称之为时间读我得到一个作为回应,直到我到达文件末尾。问题是在 do_update 功能:

In the main function I'm reading the contents of the file, and every time I call read I get one as a response until I reach the end of the file. The problem is in the do_update function:

void do_update() {
    FILE *my_file;
    int files_read;
    struct my_struct an_struct;
    struct my_struct another_struct;

    my_files = fopen("myfile.dat", "wb+"); //Using rb+ solves it

    files_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file);
    printf("do_update->files_read: %d \n", files_read); 
    //This printed zero!. Prints one using rb+

    while (files_read == 1) { //This never gets executed. Unless you use rb+

        if(something){
            fwrite(&another_struct, sizeof(struct my_struct), 1, my_file); 
            // Using rb+, this returns zero and didn't update
        }
        files_read = fread(&an_struct, sizeof(struct my_struct), 1, my_file);
        printf("do_update->files_read: %d \n", files_read);     
    }

    fclose(my_file);
}

这是怎么回事的是, files_read 变量获得零后的值通话,所以逻辑更新文件永远不会执行。

What's happening is that the files_read variable gets the value of zero after the read call, so the logic to update the file is never executed.

为什么返回零WB +打开一个文件

Why is read returning zero when opening a file for wb+?

更新:
使用 RB + 作为 do_update文件模式()的作品,但是现在调用 FWRITE( )总是返回零,并没有更新文件。是事关模式?

Update: Using rb+ as file mode on do_update() works, but now the call to fwrite() always returns zero, and it didn't update the file. Is is related to the mode?

推荐答案

FWRITE 移动文件到文件末尾的位置。在 FREAD 再没有什么阅读。

fwrite is moving the position in the file to the end of the file. The fread then has nothing to read.

使用 fgetpos 保存在 FWRITE fsetpos 来设置后的位置后面的 FWRITE

Use fgetpos to save the file position before the fwrite, and fsetpos to set the position back after the fwrite.

这篇关于C:用于读取一指针和用于更新同一文件中的一个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆