简体   繁体   中英

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:

  • ptr − This is the pointer to the array of elements to be written.
  • size − This is the size in bytes of each element to be written.
  • nmemb − This is the number of elements, each one with a size of size bytes.
  • stream − This is the pointer to a FILE object that specifies an output stream.

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM