0
0
Cprogramming~5 mins

Opening and closing files

Choose your learning style9 modes available
Introduction

We open files to read or write data. Closing files saves changes and frees resources.

When you want to save user input to a file.
When you need to read data from a file for your program.
When you want to update or add information to an existing file.
When you finish working with a file and want to release it properly.
Syntax
C
FILE *file_pointer = fopen("filename.txt", "mode");
// work with the file
fclose(file_pointer);

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

"mode" is how you want to use the file: "r" for reading, "w" for writing, "a" for appending.

Examples
Open a file named data.txt to read its contents, then close it.
C
FILE *fp = fopen("data.txt", "r");
// read from file
fclose(fp);
Open a file named log.txt to write new data, overwriting old content, then close it.
C
FILE *fp = fopen("log.txt", "w");
// write to file
fclose(fp);
Open notes.txt to add data at the end without deleting existing content, then close it.
C
FILE *fp = fopen("notes.txt", "a");
// add data to file
fclose(fp);
Sample Program

This program opens a file named example.txt for writing, writes a message, closes the file, and prints a confirmation.

C
#include <stdio.h>

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

Always check if fopen returns NULL to avoid errors when opening files.

Closing files with fclose is important to save data and free system resources.

Summary

Use fopen to open files with a mode like "r", "w", or "a".

Always close files with fclose after finishing work.

Check if fopen returns NULL to handle errors safely.