Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

fread — C23 stream function

`fread(ptr, size, nmemb, stream)` from `<stdio.h>` attempts to read `nmemb` elements of `size` bytes into array `ptr` and returns the number of completely read elements. Data is treated as a sequence of `unsigned char`; a short count means end of file or failure.

Version: C23

Syntax

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

fread(ptr, size, nmemb, stream) from <stdio.h> attempts to read nmemb elements of size bytes into array ptr and returns the number of completely read elements. Data is treated as a sequence of unsigned char; a short count means end of file or failure.

The example stores five bytes ABCDE, then twice requests three bytes. Output 3 2 1 ABC DE demonstrates a complete first read, the two bytes available to the second read, and a set end-of-file indicator.

The destination must hold size * nmemb; compute that capacity without overflow. If size == 0 or nmemb == 0, the function returns zero without changing the array or stream state. After a short count use feof and ferror; consume only complete elements because a partial element does not increment the result.

Examples

#include <stdio.h>
int main(void){FILE*s=tmpfile();if(!s)return 1;if(fwrite("ABCDE",1,5,s)!=5){fclose(s);return 1;}rewind(s);char a[4]={0},b[4]={0};size_t n1=fread(a,1,3,s),n2=fread(b,1,3,s);printf("%zu %zu %d %s %s\n",n1,n2,feof(s)!=0,a,b);return fclose(s)==0?0:1;}

Result

3 2 1 ABC DE

The example stores five bytes `ABCDE`, then twice requests three bytes. Output `3 2 1 ABC DE` demonstrates a complete first read, the two bytes available to the second read, and a set end-of-file indicator.

Sources