The fread function reads data from a file, passed as a pointer to a FILE structure. The function will put the data in a buffer that is passed as a parameter, along with the number of bites that should be read. The return value of the fread function should be the number of characters actually read.

The following signature for fread is defined in the stdio.h header file:

size_t fread(void *BUF, size_t SIZE, size_t COUNT, FILE *FP);

The fread function requires three arguments. The first argument is a pointer to the destination memory buffer. The second argument is the size of each element that is being read into the buffer. The third argument is an integer value which determines the size of the memory block that is to be read. Finally, the fourth argument is a pointer to the FILE structure that represents the file being read.

The following code shows an example of fread use:


int main()
   char buffer[50];
   int i, nchars;
   FILE *f = fopen("test", "w");
   fprintf(f, "this is the content");
   f = fopen("test", "r");
   nchars = fread(buffer, 1, 50, f);
   for (i=0; i
Article created on 2008-08-19 21:56:18

Post a comment