简体   繁体   English

C中的fread / fwrite

[英]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 . 假设src_data是我想写入dst_file

I can't quite figure out how to use fwrite . 我无法弄清楚如何使用fwrite I know that fwrite requires four parameters: 我知道fwrite需要四个参数:

  • ptr − This is the pointer to the array of elements to be written. ptr - 这是指向要写入的元素数组的指针。
  • size − This is the size in bytes of each element to be written. size - 这是要写入的每个元素的大小(以字节为单位)。
  • nmemb − This is the number of elements, each one with a size of size bytes. nmemb - 这是元素的数量,每个元素的大小都是字节大小。
  • stream − This is the pointer to a FILE object that specifies an output stream. stream - 这是指向输出流的FILE对象的指针。

But the problem I run into is that *dst_file is of const char type. 但我遇到的问题是*dst_fileconst char类型。 How can I convert this into the appropriate type to be able to use fwrite ? 如何将其转换为适当的类型才能使用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. 对于类似的问题fread为好。

First read the ref twice : fwrite() and fread() . 首先读取ref 两次fwrite()fread()

The last parameter should be a file ponter, so do it like this: 最后一个参数应该是文件ponter,所以这样做:

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. const char实际上是一个字节类型,您可以将它强制转换为您想要的任何类型。 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. 此外,您可以构建文件以具有标题,该标题告诉您存储的数据类型以及存储的数据数量,这允许您在单个文件中具有变量结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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