fwrite() in C - Source Code Example

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

fwrite() Function Overview

The fwrite() function is used in C programming when you want to write data to a file. It's like you have some information in your computer's memory and you want to save it onto your disk for later. fwrite() helps with that, making sure your data is safely written to a file.

Source Code Example

#include <stdio.h>

int main() {
    FILE *filePtr;
    char data[] = "Hi, Ram! This is a note.";  // This is our letter

    // We try to open a file to put our letter inside
    filePtr = fopen("note_to_ram.txt", "w");
    if (filePtr == NULL) {
        printf("Oh no! Couldn't create the file.\n");
        return 1;
    }

    // Using fwrite, we put our letter in the file
    fwrite(data, sizeof(char), sizeof(data) - 1, filePtr);  // -1 because we don't want to write the end-of-string character

    printf("Saved our note in the file!\n");

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

    return 0;
}

Output

The program will tell you:
Saved our note in the file!

And if you open "note_to_ram.txt", you'll find:
Hi, Ram! This is a note.

Explanation

Let's go step by step:

1. First, we prepared our note (the data array).

2. We decided to save it in a file named "note_to_ram.txt".

3. fwrite() came in handy to save our note in that file.

4. After telling us it saved the note, the program closed the file.

This is a simple way to use fwrite(). It's a start and helps you understand the basics of saving things in a file.


Comments