Latest web development tutorials

C library functions - fread ()

C standard library - <stdio.h> C standard library - <stdio.h>

description

C library functionssize_t fread (void * ptr, size_t size, size_t nmemb, FILE * stream) from a given flow streamto read the data pointedto by ptrarray.

statement

Here is the fread () function's declaration.

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

parameter

  • ptr - This is a pointer to a pointer to a block of memory with a minimum sizesize * nmembbytes.
  • size - this is the size of each element to be read in bytes.
  • nmemb - This is the number of elements, the size of each element is size bytes.
  • stream - This is a pointer to FILE pointer to an object, the object specifies a FILE input stream.

return value

The total number of elements successfully read the object will return to size_t, size_t object is an integer data type. If the total number of nmemb different parameters, it is possible that an error occurred or until the end of the file.

Examples

The following example demonstrates the fread () function is used.

#include <stdio.h>
#include <string.h>

int main()
{
   FILE *fp;
   char c[] = "This is w3cschool";
   char buffer[20];

   /* 打开文件用于读写 */
   fp = fopen("file.txt", "w+");

   /* 写入数据到文件 */
   fwrite(c, strlen(c) + 1, 1, fp);

   /* 查找文件的开头 */
   fseek(fp, SEEK_SET, 0);

   /* 读取并显示数据 */
   fread(buffer, strlen(c)+1, 1, fp);
   printf("%s\n", buffer);
   fclose(fp);
   
   return(0);
}

Let's compile and run the above program, which will create a filefile.txt, then write the contents of this is w3cschool.Next we usefseek () function to reset at the beginning of the write pointer to the file, the file contents are as follows:

This is w3cschool

C standard library - <stdio.h> C standard library - <stdio.h>