C++ <cstdio> - fread() Function
The C++ <cstdio> fread() function reads up to count elements, each one with a size of size bytes, from the given input stream stream and stores them in the block of memory specified by buffer. The file position indicator for the stream is advanced by the number of characters read.
The total amount of bytes read if successful is (size*count).
Syntax
size_t fread ( void * buffer, size_t size, size_t count, FILE * stream );
Parameters
buffer |
Specify pointer to a block of memory with a size of at least (size*count) bytes, converted to a void*. |
size |
Specify size, in bytes, of each element to be read. size_t is an unsigned integral type. |
count |
Specify number of elements, each one with a size of size bytes. size_t is an unsigned integral type. |
stream |
Specify a pointer to a FILE object that specifies an input stream. |
Return Value
Returns the total number of elements successfully read. It may be less than count if an error or end-of-file condition occurs. In both cases, the proper indicator is set, which can be checked with ferror() and feof(), respectively.
If size or count is zero, fread() returns zero and performs no other action.
Example: fread() example
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
In the example below, the fread() function is used to read the content of this file.
#include <cstdio> #include <cstdlib> int main (){ long lSize; char * buffer; //open the file in read mode FILE *pFile = fopen("test.txt", "r"); //obtain file size fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); //allocate memory to buffer to contain the whole file buffer = (char*) malloc (sizeof(char)*lSize); //read and display the whole file fread(buffer, 1, lSize, pFile); printf("%s", buffer); //close the file fclose(pFile); return 0; }
The output of the above code will be:
This is a test file. It contains dummy content.
Example: fread() and fwrite() example
Consider one more example where at first fwrite() function is used to write some content to a text file then fread() function is used to read the content of this file.
#include <cstdio> #include <cstring> int main (){ char c[] = "Hello World!"; char buffer [100]; //open the file in write and read mode FILE *pFile = fopen("test.txt", "w+"); //write data to the file fwrite(c, strlen(c) + 1, 1, pFile); //seek to the beginning of the file fseek(pFile, 0, SEEK_SET); //read and display data fread(buffer, strlen(c)+1, 1, pFile); printf("%s\n", buffer); //close the file fclose(pFile); return 0; }
The output of the above code will be:
Hello World!
❮ C++ <cstdio> Library