fread() in C - Source Code Example

In this source code example, we will see how to use the fread() function in C programming with an example.

Function Overview

In C, the fread() function lets you read data from a file. This is handy when you need to pull data from a file you've saved before. fread() reads a bunch of data bits (or bytes) from a file and puts them in a spot in your program, like an array or a variable.

Source Code Example

#include <stdio.h>

int main() {
    FILE *filePtr;
    char data[20];  // This will hold the data we read

    // We're trying to open a file in read mode
    filePtr = fopen("example.txt", "r");
    if (filePtr == NULL) {
        printf("Oops! Couldn't open the file.\n");
        return 1;
    }

    // We use fread to pull out the file's content
    fread(data, sizeof(char), sizeof(data), filePtr);
    printf("Data from the file: %s\n", data);

    // Always close the file when you're done
    fclose(filePtr);

    return 0;
}

Output

If "example.txt" has the words "Hello Ram!", then the output will be:
Data from the file: Hello Ram!

Explanation

Here's the simple breakdown:

1. We wanted to open a file named "example.txt" to see what's inside.

2. We had a spot (the data array) ready to keep what we read.

3. Using fread(), we got the content and put it in our data spot.

4. Then, we showed the data on the screen.

5. At the end, we remembered to close the file.

It's a basic way to use fread(). There are more details to learn, but this is a good start for beginners.


Comments