Built with Tutify.io

    AIStudyLabs

    Introduction to File Handling

    Introduction to File Handling

    Introduction

    In this lesson, we will delve into file handling in C. Understanding how to manage files is a vital skill for any programmer, as it allows us to read from and write to files, making our programs capable of persistent data storage. We will cover file operations such as opening, closing, reading, and writing, as well as explore standard file handling functions along with error handling techniques. Finally, we will discuss file positioning functions that enable us to navigate through files efficiently.

    File Operations in C

    Basic Operations

    File handling in C involves several fundamental operations, which include:

    Code Example of File Operations

    #include <stdio.h>
    
    int main() {
        FILE *file;
        file = fopen("example.txt", "w"); // Open file for writing
        if (file == NULL) {
            printf("Error opening file!\n");
            return 1;
        }
        fprintf(file, "Hello, File Handling in C!\n"); // Write to the file
        fclose(file); // Close the file
        return 0;
    }
    

    Program Explanation:

    Output: (No output to console, but example.txt will contain)

    Hello, File Handling in C!
    

    Standard File Handling Functions

    1. fopen: Used to open a file.

      • Syntax: FILE *fopen(const char *filename, const char *mode);
      • Modes include: "r" (read), "w" (write), "a" (append).
    2. fclose: Closes a file stream.

      • Syntax: int fclose(FILE *stream);
    3. fread: Reads data from a file.

      • Syntax: size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
    4. fwrite: Writes data to a file.

      • Syntax: size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

    Text vs. Binary File Handling

    Text Files

    Text files store data in human-readable format.

    Binary Files

    Binary files store data in a format that is not human-readable. This is often used for non-text files.

    Code Example: Binary File Handling

    #include <stdio.h>
    #include <stdlib.h>
    
    struct Data {
        int value;
    };
    
    int main() {
        struct Data data = { 123 }; // Sample data
        FILE *file = fopen("data.bin", "wb");
        fwrite(&data, sizeof(data), 1, file);
        fclose(file);
        return 0;
    }
    

    Program Explanation:

    Output: (No output directly visible. A binary file data.bin is created.)

    Error Handling in File Operations

    Effective error handling is critical. Always check if the file was opened successfully by checking the return value of fopen. If it returns NULL, an error occurred. Always include error checking for file operations to ensure the program behaves as expected under all circumstances.

    Code Example for Error Handling

    int main() {
        FILE *file;
        file = fopen("non-existent-file.txt", "r"); // Attempt to open a non-existing file
        if (file == NULL) {
            perror("Error opening file"); // Print error message
            return 1;
        }
        fclose(file);
        return 0;
    }
    

    Output:
    The output will display a system error message indicating that the file could not be opened.

    File Positioning Functions

    File positioning allows you to navigate through files:

    Code Example: Using Positioning Functions

    #include <stdio.h>
    
    int main() {
        FILE *file;
        file = fopen("example.txt", "r");
        fseek(file, 0, SEEK_END);  // Move to the end
        long size = ftell(file);    // Get current position
        rewind(file);               // Move back to the beginning
        printf("File size: %ld bytes\n", size);
        fclose(file);
        return 0;
    }
    

    Program Explanation:

    Output:
    File size: <size> bytes
    (Where <size> is the byte size of the file.)

    Summary / Key Takeaways

    C Programming Fundamentals: From Zero to Confident C Coder — File Handling in C

    Introduction to Programming and C

    Variables and Data Types

    Control Structures: Conditions and Loops

    Functions in C

    Arrays and Strings

    Working with Pointers

    File Handling in C

    Structures and Unions in C

    Project Development and Implementation

    Advanced C Concepts and Best Practices

    Tutorial Not Found