Built with Tutify.io

    AIStudyLabs

    Reading from and Writing to Files

    Reading from and Writing to Files

    Introduction

    In this lesson, we will delve into file handling in C programming, specifically focusing on how to read from and write to files effectively. You will understand the importance of file pointers and learn how to manipulate files using various C functions. This lesson will provide practical examples and best practices to ensure that you manage file operations and errors gracefully.

    Understanding File Pointers in C Programming

    A file pointer in C is a pointer that is used to manage file operations. It points to a file's location in memory and is essential for performing reading and writing operations.

    To declare a file pointer, we use:

    FILE *fp;
    

    Where FILE is a structure defined in the standard library to represent a file stream. This allows us to manipulate files via the declared pointer.

    Opening and Closing Files Correctly

    To interact with files, we first need to open them. Use the fopen() function, which requires the name of the file and the mode of access:

    fp = fopen("example.txt", "r"); // Open for reading
    

    The modes include:

    Closing a file is equally important to ensure that resources are released. This is done using:

    fclose(fp);
    

    Reading Data from Text Files

    Reading from a file can be done using functions such as fscanf() and fgets(). Consider the following example that reads data from a text file line by line:

    #include <stdio.h>
    
    int main() {
        FILE *fp;
        char buffer[100];
        fp = fopen("example.txt", "r");
    
        if (fp == NULL) {
            printf("Error opening file.\n");
            return 1;
        }
    
        while (fgets(buffer, sizeof(buffer), fp) != NULL) {
            printf("%s", buffer); // Print each line
        }
    
        fclose(fp);
        return 0;
    }
    

    Output:

    First Line of the file  
    Second Line of the file  
    

    This program reads a file named example.txt and prints each line to the console. The fgets() function is used here as it reads a complete line including spaces until a newline character is encountered or the buffer size limit is reached.

    Writing Data to Files Effectively

    Writing to a file is done using functions such as fprintf() or fputs(). Below is an example that shows how to write user-provided data to a file:

    #include <stdio.h>
    
    int main() {
        FILE *fp;
        char data[100];
        fp = fopen("output.txt", "w");
    
        if (fp == NULL) {
            printf("Error creating file.\n");
            return 1;
        }
    
        printf("Enter data to write to the file: ");
        fgets(data, sizeof(data), stdin);
        fprintf(fp, "%s", data); // Write data to file
    
        fclose(fp);
        return 0;
    }
    

    Output: This program enables a user to input text that will be saved in output.txt. The function fprintf() effectively formats the output, writing the provided string into the file.

    Handling File Errors and Exceptions Gracefully

    Error handling is critical while performing file operations. After attempting to open a file, always check if the file pointer is NULL. This indicates that an error occurred during the file opening:

    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    

    This method helps prevent runtime errors and ensures that your program behaves predictably when faced with unexpected situations, like permission issues or missing files.

    Summary / Key Takeaways

    In this lesson on Reading from and Writing to Files, you have learned:

    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