File Handling in C: Understanding File Operations and Modes

C Programming @ Freshers.in

File handling is a fundamental aspect of C programming, allowing you to perform various operations on files. In this comprehensive guide, we’ll delve into the world of file handling in C, focusing on file operations and modes. Real-world examples with outputs will clarify the concepts and help you become proficient in working with files in C.

Introduction to File Operations and Modes

File operations in C encompass a range of actions such as opening, reading, writing, appending, and closing files. The choice of file mode determines the type of operation that can be performed on a file. We will explore commonly used file modes in this article.

File Modes

1. Reading Mode ("r")

  • Used for reading an existing file.
  • File must exist; otherwise, it returns NULL.

Example: Reading a Text File

#include <stdio.h>
int main() {
    FILE *file;
    char ch;
    // Open a text file for reading
    file = fopen("sample.txt", "r");
    if (file == NULL) {
        printf("File not found or unable to open.\n");
        return 1;
    }
    // Read and print the contents character by character
    while ((ch = fgetc(file)) != EOF) {
        printf("%c", ch);
    }
    // Close the file
    fclose(file);
    return 0;
}

2. Writing Mode ("w")

  • Used for creating a new file or overwriting an existing file.
  • If the file exists, its previous content is deleted.

Example: Writing to a Text File

#include <stdio.h>
int main() {
    FILE *file;
    // Open a text file for writing
    file = fopen("output.txt", "w");
    if (file == NULL) {
        printf("Unable to create or open the file.\n");
        return 1;
    }
    // Write data to the file
    fprintf(file, "This is a sample text written to a file.\n");
    // Close the file
    fclose(file);
    return 0;
}

3. Appending Mode ("a")

  • Used for appending data to an existing file.
  • If the file does not exist, a new file is created.

Example: Appending to a Text File

#include <stdio.h>
int main() {
    FILE *file;
    // Open a text file for appending
    file = fopen("log.txt", "a");
    if (file == NULL) {
        printf("Unable to create or open the file.\n");
        return 1;
    }
    // Append data to the file
    fprintf(file, "This is an appended line.\n");
    // Close the file
    fclose(file);
    return 0;
}

File operations and modes are essential for tasks such as:

  • Reading and processing data from external files (e.g., input files).
  • Creating and managing log files for applications.
  • Writing and storing program configurations.
Author: user