0
0
Cprogramming~5 mins

File modes in C

Choose your learning style9 modes available
Introduction
File modes tell the computer how you want to open a file, like reading, writing, or adding new data.
When you want to read data from a file, like loading a saved game.
When you want to write new data to a file, like saving a document.
When you want to add information to the end of an existing file, like adding a new message to a log.
When you want to create a new file or overwrite an old one.
When you want to read and write to the same file without closing it.
Syntax
C
FILE *fopen(const char *filename, const char *mode);
The mode is a string that tells fopen how to open the file.
Common modes include "r" for read, "w" for write, and "a" for append.
Examples
Open the file "data.txt" for reading only.
C
FILE *file = fopen("data.txt", "r");
Open the file "output.txt" for writing. If it exists, it will be cleared.
C
FILE *file = fopen("output.txt", "w");
Open the file "log.txt" to add new data at the end.
C
FILE *file = fopen("log.txt", "a");
Open the file "data.bin" for reading in binary mode.
C
FILE *file = fopen("data.bin", "rb");
Sample Program
This program writes a message to a file using write mode ("w") and then reads it back using read mode ("r").
C
#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    if (file == NULL) {
        printf("Failed to open file.\n");
        return 1;
    }
    fprintf(file, "Hello, file modes!\n");
    fclose(file);

    file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Failed to open file.\n");
        return 1;
    }
    char buffer[50];
    if (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("Read from file: %s", buffer);
    }
    fclose(file);
    return 0;
}
OutputSuccess
Important Notes
Always check if fopen returns NULL to make sure the file opened successfully.
Using "w" mode will erase the file content if it already exists.
Use "b" in the mode (like "rb" or "wb") when working with binary files.
Summary
File modes tell the program how to open a file: read, write, or append.
Use "r" to read, "w" to write (and clear), and "a" to add at the end.
Always check if the file opened successfully before using it.