C Library Function - fread()
C Standard Library - <stdio.h>
Description
The C library function sizet fread(void *ptr, sizet size, size_t nmemb, FILE *stream) reads data from the given stream stream into the array pointed to by ptr.
Declaration
Here is the declaration for the fread() function.
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
Parameters
ptr -- This is a pointer to a block of memory with a minimum size of sizenmemb* bytes.
size -- This is the size of each element to be read, in bytes.
nmemb -- This is the number of elements, each one with a size of size bytes.
stream -- This is a pointer to a FILE object that specifies an input stream.
Return Value
The total number of elements successfully read is returned as a size_t object, which is an integer data type. If this number differs from the nmemb parameter, either a reading error occurred or the end of the file was reached.
Example
The following example demonstrates the use of the fread() function.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char c[] = "This is tutorialpro";
char buffer[20];
/* Open file for both reading and writing */
fp = fopen("file.txt", "w+");
/* Write data to the file */
fwrite(c, strlen(c) + 1, 1, fp);
/* Seek to the beginning of the file */
fseek(fp, 0, SEEK_SET);
/* Read and display data */
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 file file.txt and write the content This is tutorialpro to it. Then we use the fseek() function to reset the write pointer to the beginning of the file. The file content will be as follows:
This is tutorialpro