6.18.28 fwrite Function

Writes data to the stream.

Attention: This function is not implemented by MPLAB XC8 for PIC MCUs. It is implemented by all other compilers, but MPLAB XC8 for AVR MCUs has limited support of data streams.

Include

<stdio.h>

Prototype

size_t fwrite(const 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 open stream

Return Value

Returns the number of complete elements successfully written, which will be less than nelem only if a write error is encountered.

Remarks

The function writes characters to a given stream from a buffer pointed to by ptr up to nelem elements whose size is specified by size. The file position indicator is advanced by the number of characters successfully written. 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.