mercredi 4 novembre 2015

Fast and efficient way of writing an array of structs to a text file

I have a binary file. I am reading a block of data from that file into an array of structs using fread method. My struct looks like below.

struct Num {
    uint64_t key;
    uint64_t val

My main goal is to write the array into a different text file with space separated key and value pairs in each line as shown below.

Key1 Val1
Key2 Val2
Key3 Val3

I have written a simple function to do this.

Num *buffer = new Num[buffer_size];
// Read a block of data from the binary file into the buffer array.
ofstream out_file(OUT_FILE, ios::out);
for(size_t i=0; i<buffer_size; i++)
    out_file << buffer[i].key << ' ' << buffer[i].val << '\n';

The code works. But it's slow. One more approach would be to create the entire string first and write to file only once at the end.

But I want to know if there are any best ways to do this. I found some info about ostream_iterator. But I am not sure how it works.

Aucun commentaire:

Enregistrer un commentaire