0
0
Cprogramming~5 mins

Why file handling is required in C

Choose your learning style9 modes available
Introduction

File handling lets programs save and read data from files. This helps keep information even after the program stops.

Saving user settings so they stay the same next time the program runs.
Storing game scores to show high scores later.
Reading a list of names or data from a file to use in the program.
Logging errors or events while the program runs for later review.
Syntax
C
FILE *file_pointer;
file_pointer = fopen("filename.txt", "mode");
// Use file_pointer to read or write
fclose(file_pointer);

"filename.txt" is the name of the file you want to open or create.

"mode" tells if you want to read ("r"), write ("w"), or append ("a") to the file.

Examples
Open the file "data.txt" for reading.
C
FILE *fp;
fp = fopen("data.txt", "r");
Open the file "output.txt" for writing. If it doesn't exist, it will be created.
C
FILE *fp;
fp = fopen("output.txt", "w");
Open the file "log.txt" to add new data at the end without deleting existing content.
C
FILE *fp;
fp = fopen("log.txt", "a");
Sample Program

This program creates a file named "example.txt" and writes a message into it. It then closes the file and prints a success message.

C
#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("example.txt", "w");
    if (fp == NULL) {
        printf("Error opening file\n");
        return 1;
    }
    fprintf(fp, "Hello, file handling!\n");
    fclose(fp);
    printf("Data written to file successfully.\n");
    return 0;
}
OutputSuccess
Important Notes

Always check if the file opened successfully before reading or writing.

Remember to close the file after finishing to save changes and free resources.

Summary

File handling helps save data permanently outside the program.

It is useful for reading, writing, and appending data to files.

Opening and closing files properly is important to avoid errors.