- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
fread() function in C++
The C/C++ library function size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) reads data from the given stream into the array pointed to, by ptr. Following is the declaration for fread() function.
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
The Following table contains the fread() parameters and description:
Parameters | Description |
---|---|
ptr | This is the pointer to a block of memory with a minimum size of size*nmemb bytes. |
size | This is the size in bytes of each element to be read. |
nmemb | This is the number of elements, each one with a size of size bytes. |
stream | This is the pointer to a FILE object that specifies an input stream. |
The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached.
Example Code
#include <stdio.h> #include <string.h> int main () { FILE *fp; char c[] = "this is tutorialspoint"; char buffer[100]; /* 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 us compile and run the above program that will create a file file.txt and write a content this is tutorialspoint. After that, we use fseek() function to reset writing pointer to the beginning of the file and prepare the file content which is as follows −
Output
this is tutorialspoint