Next: freopen, Previous: fputws, Up: Stdio [Contents][Index]

### 4.24 `fread`, `fread_unlocked`—read array elements from a file

Synopsis

    #include <stdio.h>
    size_t fread(void *restrict buf, size_t size, size_t count,
        FILE *restrict fp);

    #define _BSD_SOURCE
    #include <stdio.h>
    size_t fread_unlocked(void *restrict buf, size_t size, size_t count,
        FILE *restrict fp);

    #include <stdio.h>
    size_t _fread_r(struct _reent *ptr, void *restrict buf,
        size_t size, size_t count, FILE *restrict fp);

    #include <stdio.h>
    size_t _fread_unlocked_r(struct _reent *ptr, void *restrict buf,
        size_t size, size_t count, FILE *restrict fp);

Description
`fread` attempts to copy, from the file or stream identified by fp, count elements (each of size size) into memory, starting at buf. `fread` may copy fewer elements than count if an error, or end of file, intervenes.

`fread` also advances the file position indicator (if any) for fp by the number of characters actually read.

`fread_unlocked` is a non-thread-safe version of `fread`. `fread_unlocked` may only safely be used within a scope protected by flockfile() (or ftrylockfile()) and funlockfile(). This function may safely be used in a multi-threaded program if and only if they are called while the invoking thread owns the (FILE *) object, as is the case after a successful call to the flockfile() or ftrylockfile() functions. If threads are disabled, then `fread_unlocked` is equivalent to `fread`.

`_fread_r` and `_fread_unlocked_r` are simply reentrant versions of the above that take an additional reentrant structure pointer argument: ptr.

Returns
The result of `fread` is the number of elements it succeeded in reading.

Portability
ANSI C requires `fread`.

`fread_unlocked` is a BSD extension also provided by GNU libc.

Supporting OS subroutines required: `close`, `fstat`, `isatty`, `lseek`, `read`, `sbrk`, `write`.

Next: freopen, Previous: fputws, Up: Stdio [Contents][Index]