Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from and writing to the middle of a binary file in C/C++

Tags:

c++

c

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?
}
like image 589
Switch Avatar asked Nov 08 '09 07:11

Switch


1 Answers

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.

like image 68
Greg Hewgill Avatar answered Sep 20 '22 16:09

Greg Hewgill