简体   繁体   English

在C中更改.bin文件的数据

[英]Changing .bin file's data in C

I have a lot of data stored in bin format as a sequence of structs. 我有很多数据以bin格式存储为一系列结构。 I want to be able to read randomly any of the structs and modify it in C. I am trying with the following code but it doesn't work. 我希望能够随机读取任何结构并在C中修改它。我正在尝试使用以下代码,但它不起作用。 Can someone fix it for me please? 有人可以帮我解决吗?

Also, would it be possible to delete an intermediate struct from the file in between? 另外,是否可以从文件中删除中间结构?

The code is below: 代码如下:

#include <stdio.h>
#include <stdlib.h>

struct rec {
        int x,y,z;
};

void f_rite()
{
        int i;
        FILE *ptr_myfile;
        struct rec my_record;

        ptr_myfile=fopen("test.bin","w");

        for ( i=0; i < 5; i++ ) {
                my_record.x = i;
                fwrite( &my_record, sizeof(struct rec), 1, ptr_myfile );
        }

        fclose(ptr_myfile);

        return;
}


void f_read()
{
        int i;
        FILE *ptr_myfile;
        struct rec my_record;

        ptr_myfile=fopen("test.bin","r");

        for ( i=1; i <= 5; i++) {
                fread(&my_record,sizeof(struct rec),1,ptr_myfile);
                printf("%d\n",my_record.x);
        }
        printf("\n");

        fclose(ptr_myfile);

        return;
}

void f_rerite()
{
        int i;
        FILE *ptr_myfile;
        struct rec my_record;

        ptr_myfile=fopen("test.bin","rw");

        for ( i=5; i >= 0; i-- ) {
                fseek( ptr_myfile, sizeof(struct rec)*i, SEEK_SET );
                fread( &my_record, sizeof(struct rec), 1, ptr_myfile );
                my_record.x = my_record.x + 100;
                fwrite( &my_record, sizeof(struct rec), 1, ptr_myfile );
        }

        fclose(ptr_myfile);

        return;
}

int main()
{
        f_rite();
        f_read();
        f_rerite();
        f_read();

        return 0;
}

There is no "rw" flag to fopen. fopen没有“rw”标志。 You need "r+" for reading and writing(updating). 你需要“r +”进行读写(更新)。 Since it's binary data, you should actually use "r+b" , and "wb" in your f_rite function and "rb" in your f_read function. 因为它是二进制数据,所以你应该在f_rite函数中使用“r + b”和“wb”,在f_read函数中使用“rb”。 Also: 也:

  • Check the return value of calls that could fail, you'd discover that eg fwrite failed. 检查可能失败的调用的返回值,您会发现例如fwrite失败。
  • Your f_rerite functions iterates through 6 elements, you're off by one. 你的f_rerite函数遍历6个元素,你就一个接一个。
  • Your f_rerite also writes to the next element. 您的f_rerite也会写入下一个元素。 Likely you want to update the current record rather. 可能你想更新当前的记录。 Which means you need to fseek again after calling fread. 这意味着你在调用fread之后需要再次尝试。

"rw" is wrong. "rw"错了。 Use "r+" . 使用"r+" Don't forget to seek back after reading. 阅读后别忘了回头看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM