In this section, we will learn what the freed() function is and how it works in C.
C Read from File: C freed() Function
The `fread()` function is used to read binary content from a file.
C fread() Function Syntax:
Here’s the prototype of the function:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
C fread() Function Parameters
This function takes 4 arguments:
- The first argument is the address of the memory space that incoming data should be stored into.
- The second argument represents the size, in bytes, of the chunks to be read from the target file.
- The third argument represents the number of chunks to be read.
- The last argument identifies the file to read from.
C fread() Function Return Value
The returned value of the function on a successful operation is equal to its third argument, which is the number of chunks. If any other number returned, it means an error happened.
Example: reading from a file in C
#include <stdio.h>
#include <stdlib.h>
int main() {
char buffer[] = "C programming is cool!";
FILE *file = fopen("G:/fileOne.txt","w+");
if (file == NULL){
printf("Could not open the file");
exit(EXIT_FAILURE);
}
fwrite(buffer, sizeof(buffer), 1, file);
rewind(file);
char stored[sizeof(buffer)];
fread(stored, sizeof(buffer), 1, file);
printf("%s",stored);
fclose(file);
printf("\nDone\n");
return 0;
}
Output:
C programming is cool! Done
How Does fread() Function Work in C?
In this example, we first stored a character-string into a file in its binary form via the call to the `fwrite()` function and then via the call to the `fread()` function we took back that data from the file and stored it in another memory-space.