在C/C++中读取和写入二进制文件的中间

Swi*_*tch 6 c c++

如果我有一个大的二进制文件(假设它有100,000,000个浮点数),C(或C++)中有没有办法打开文件并读取特定的浮点数,而不必将整个文件加载到内存中(即我怎样才能快速找到第62,821,214号浮标是什么)?第二个问题,有没有办法在不必重写整个文件的情况下更改文件中的特定浮点数?

我想象的功能如下:

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?
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 19

你知道浮点数的大小sizeof(float),所以乘法可以到达正确的位置:

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

同样,您可以使用此方法写入特定位置.