Mike Henke
Mike Henke

Reputation: 643

fread/fwrite in C

Let's say I have these parameters:

bool array_serialize(const void *src_data,
                const char *dst_file,
                const size_t elem_size,
                const size_t elem_count);

Assume that src_data is the array I'd like to write into dst_file.

I can't quite figure out how to use fwrite. I know that fwrite requires four parameters:

But the problem I run into is that *dst_file is of const char type. How can I convert this into the appropriate type to be able to use fwrite? I've tried doing

fwrite(src_data, elem_size, elem_count, dst_file);

but obviously this is incorrect.

Similar question for fread as well.

Upvotes: 1

Views: 2402

Answers (2)

DAhrens
DAhrens

Reputation: 380

const char is effectively a byte type, you can cast it to any type you want to. If you have a binary file stored with a known pattern (you better) you read the type by the member size into your target struct.

So for instance if you have a struct with two variables

struct foo {
  int f1;
  int f2;
};

And you know that the entire file is made up of these, then you can fread the values from the file like this

fread(&target, sizeof(foo), num_elems, fp)

You can rinse and repeat this based on the file you are reading or writing.

Additionally you can structure the file to have headers which tell you what type of data is stored, and how many of them there are, which allows you to have variable structures in a single file.

Upvotes: 0

gsamaras
gsamaras

Reputation: 73366

First read the ref twice: fwrite() and fread().

The last parameter should be a file ponter, so do it like this:

fp = fopen(dst_file, "w+");
if(fp != NULL) {
    fwrite(src_data, elem_size, elem_count, fp);
    rewind(fp);
    fread(result_data, elem_size, elem_count, fp);
}

Take a look on more examples.

Upvotes: 3

Related Questions