读取和写入到C / C二进制文件的中间++ [英] Reading from and writing to the middle of a binary file in C/C++

查看:96
本文介绍了读取和写入到C / C二进制文件的中间++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个大的二进制文件(说它亿花车),是否有在C(或C ++)的方式打开文件并读取特定浮动,而无需将整个文件加载到内存(即如何我能很快找到第六千二百八十二万一千二百十四浮动是什么)?第二个问题,有没有办法来改变文件中的具体浮动而不必重写整个文件?

我预想的功能,如:

 浮动readFloatFromFile(为const char *文件名,INT IDX){
    FILE * F = FOPEN(文件名,RB);    //善有善报吗?
}无效writeFloatToFile(为const char *文件名,INT IDX,浮动F){
    //我如何打开这个文件? FOPEN只能追加或启动一个新的文件,对不对?    //善有善报吗?
}


解决方案

您知道一个浮动的大小的sizeof(浮动),所以乘法可以让你的正确位置:

  FILE * F = FOPEN(文件名,RB);
fseek的(F,IDX *的sizeof(浮动),SEEK_SET);
float结果;
FREAD(安培;结果的sizeof(浮动),1,F);

同样的,你可以写信给使用这种方法的特定位置。

If I have a large binary file (say it has 100,000,000 floats), is there a way in C (or C++) to open the file and read a specific float, without having to load the whole file into memory (i.e. how can I quickly find what the 62,821,214th float is)? A second question, is there a way to change that specific float in the file without having to rewrite the entire file?

I'm envisioning functions like:

float readFloatFromFile(const char* fileName, int idx) {
    FILE* f = fopen(fileName,"rb");

    // What goes here?
}

void writeFloatToFile(const char* fileName, int idx, float f) {
    // How do I open the file? fopen can only append or start a new file, right?

    // What goes here?
}

解决方案

You know the size of a float is sizeof(float), so multiplication can get you to the correct position:

FILE *f = fopen(fileName, "rb");
fseek(f, idx * sizeof(float), SEEK_SET);
float result;
fread(&result, sizeof(float), 1, f);

Similarly, you can write to a specific position using this method.

这篇关于读取和写入到C / C二进制文件的中间++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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