##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# fread

From cppreference.com
< c‎ | io

Defined in header `<stdio.h>` |  |

size_t fread( void *buffer, size_t size, size_t count, FILE *stream ); |  | (until C99)
size_t fread( void *restrict buffer, size_t size, size_t count, FILE *restrict stream ); |  | (since C99)

Reads specified number of objects in the array `buffer` from the given input stream `stream`. Objects are not interpreted in any way.

### [edit] Parameters

buffer | - | pointer to the array where the read objects are stored
size | - | size of each object in bytes
count | - | the number of the objects to be read
stream | - | the stream to read

### [edit] Return value

The number of objects read successfully.

### [edit] Example

fread with error checking

Run this code

    #include <stdio.h>
    #include <stdlib.h>

    int main(void)
    {
        /* Prepare an array of f-p values. */
        #define SIZE 5
        double A[SIZE] = {1.,2.,3.,4.,5.};
        /* Write array to a file. */
        FILE * fp = fopen("test.bin", "wb");
        fwrite(A,sizeof(double),SIZE,fp);
        fclose (fp);

        /* Read the f-p values into array B. */
        double B[SIZE];
        fp = fopen("test.bin","rb");
        int ret_code = fread(B,sizeof(double),SIZE,fp);
        if (ret_code < SIZE)
        {
           if (feof(fp))
              printf("EOF reached\n");
           else if (ferror(fp))
                {
                  perror("fread()");
                  fprintf(stderr,"fread() failed in file %s at line # %d\n", __FILE__,__LINE__-8);
                  exit(EXIT_FAILURE);
                }
        }
        printf("%.1f\n", B[4]);   /* print one f-p value */

        return EXIT_SUCCESS;
    }

Output:

    5.0

### [edit] See also

scanf fscanf sscanf | reads formatted input from stdin, a file stream or a buffer (function) [edit]
fgets | gets a character string from a file stream (function) [edit]
fwrite | writes to a file (function) [edit]
C++ documentation for fread

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=c/io/fread&oldid=69900"