fread Function

Reads data from the stream.

Attention: This function is not implemented by MPLAB XC8.

Include

<stdio.h>

Prototype

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

Arguments

ptr
pointer to the storage buffer
size
size of item
nelem
maximum number of items to be read
stream
pointer to the stream

Return Value

Returns the number of complete elements read up to nelem whose size is specified by size.

Remarks

The function reads characters from a given stream into the buffer pointed to by ptr until the function stores size * nelem characters or sets the end-of-file or error indicator. fread returns n/size where n is the number of characters it read. If n is not a multiple of size, the value of the last element is indeterminate. If the function sets the error indicator, the file-position indicator is indeterminate.

Example

#include <stdio.h>

int main(void) { 
  FILE *buf;
  int x, numwrote, numread;
  double nums[10], readnums[10];

  if ((buf = fopen("afile.out", "w+")) != NULL) {
    for (x = 0; x < 10; x++) {
      nums[x] = 10.0/(x + 1);
      printf("10.0/%d = %f\n", x+1, nums[x]);
    }
    numwrote = fwrite(nums, sizeof(double), 10, buf);
    printf("Wrote %d numbers\n\n", numwrote);
    fclose(buf);
    }
  else printf("Cannot open afile.out\n"); 

  if ((buf = fopen("afile.out", "r+")) != NULL) {
    numread = fread(readnums, sizeof(double), 10, buf);
    printf("Read %d numbers\n", numread);
    for (x = 0; x < 10; x++) {
      printf("%d * %f = %f\n", x+1, readnums[x], (x + 1) * readnums[x]);
    }
    fclose(buf);
  }
  else printf("Cannot open afile.out\n");
}

Example Output

10.0/1 = 10.000000
10.0/2 = 5.000000
10.0/3 = 3.333333
10.0/4 = 2.500000
10.0/5 = 2.000000
10.0/6 = 1.666667
10.0/7 = 1.428571
10.0/8 = 1.250000
10.0/9 = 1.111111
10.0/10 = 1.000000
Wrote 10 numbers

Read 10 numbers
1 * 10.000000 = 10.000000
2 * 5.000000 = 10.000000
3 * 3.333333 = 10.000000
4 * 2.500000 = 10.000000
5 * 2.000000 = 10.000000
6 * 1.666667 = 10.000000
7 * 1.428571 = 10.000000
8 * 1.250000 = 10.000000
9 * 1.111111 = 10.000000
10 * 1.000000 = 10.000000

Example Explanation

This program uses fwrite to save 10 numbers to a file in binary form. This allows the numbers to be saved in the same pattern of bits as the program is using, which provides more accuracy and consistency. Using fprintf would save the numbers as text strings, which could cause the numbers to be truncated. Each number is divided into 10 to produce a variety of numbers. Retrieving the numbers with fread to a new array and multiplying them by the original number shows the numbers were not truncated in the save process.