简体   繁体   中英

What do all the parameters in fread and fwrite stand for?

I started using fread and fwrite in order to send files over a tcp connection and I was wondering what the parameters for the functions stand for. I've tried reading the documentation, but I didn't understand the difference between the second parameter (size) and the third one (nmemb). Could anyone describe the purpose of every parameter and the difference between the two parameters mentioned above? Thanks.

Could anyone describe... the difference between the two parameters mentioned above?

size_t fread(void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);

size is the size of a single element being read. Eg When reading a double the size would be sizeof(double) or commonly 8.

nmemb is the max number of elements to read.

Importantly, the return value is the number of elements read, not necessarily the number of bytes read.


Could anyone describe purpose of every parameter... ?

ptr is the location in memory to begin saving the data.

stream is the FILE * pointer to use when reading, often the result of fopen() .


Sample Usage

FILE *inf = fopen("data.bin", "rb");
if (inf) {
  double data[N];
  size_t n;
  while ((n = fread(data, sizeof data[0], N, inf)) > 0) {
    printf("Read %zu doubles, first one %g\n", n, data[0]);
  }
  fclose(inf);
} 

fread and fwrite , defined in <stdio.h> (docs here ) have the following signature:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *" stream );
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
  1. Both of them require a pointer to a buffer, ptr , which would contain the starting address where data has to be copied ( fread ) or where to copy from ( fwrite )
  2. Both of them are supposed to copy nmemb elements each of size bytes. S For example, if you are copying a buffer of 100 characters

    fread( ptr, 1, 100, filePointer );

because the size of a char is 1. In the general case in which you are copying N elements of type myType

 fread( ptr, sizeof(myType), N, filePointer );

and in this case totally sizeof(myType) * N bytes will be read.

  1. They require a valid pointer to file ( FILE * ) obtained with a successfull call to the fopen function (described here ).

  2. Talking about their return value, a can't write a better descriptions than the one contained in the linked documentation:

On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).

So, on success, it will return at most nmemb .

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