File handling is an essential aspect of programming in C, allowing you to store data permanently on disk, read data from files, and manipulate file contents. This module will introduce you to the basics of file handling in C, including opening, reading, writing, and closing files.

Key Concepts

  1. File Operations: Understanding the basic operations you can perform on files.
  2. File Pointers: Using pointers to manage file operations.
  3. File Modes: Different modes for opening files.
  4. Standard Library Functions: Utilizing C standard library functions for file handling.

File Operations

In C, file handling involves the following basic operations:

  • Opening a file: Before you can read from or write to a file, you need to open it.
  • Reading from a file: Extracting data from a file.
  • Writing to a file: Adding data to a file.
  • Closing a file: Releasing the resources associated with a file.

File Pointers

A file pointer is a pointer to a structure that contains information about the file. It is used to keep track of the current position in the file and other file-related information.

FILE *filePointer;

File Modes

When opening a file, you need to specify the mode in which you want to open it. The common modes are:

Mode Description
"r" Open for reading. The file must exist.
"w" Open for writing. Creates a new file if it doesn't exist or truncates the file if it does.
"a" Open for appending. Data is added to the end of the file.
"r+" Open for both reading and writing. The file must exist.
"w+" Open for both reading and writing. Creates a new file if it doesn't exist or truncates the file if it does.
"a+" Open for both reading and appending. Data is added to the end of the file.

Standard Library Functions

C provides several standard library functions for file handling, including:

  • fopen(): Opens a file.
  • fclose(): Closes a file.
  • fread(): Reads data from a file.
  • fwrite(): Writes data to a file.
  • fgets(): Reads a string from a file.
  • fputs(): Writes a string to a file.
  • fprintf(): Writes formatted data to a file.
  • fscanf(): Reads formatted data from a file.

Practical Example

Let's look at a simple example of how to open a file, write to it, and then read from it.

Code Example

#include <stdio.h>

int main() {
    FILE *filePointer;
    char dataToWrite[] = "Hello, World!";
    char dataRead[50];

    // Open the file for writing
    filePointer = fopen("example.txt", "w");
    if (filePointer == NULL) {
        printf("Failed to open the file.\n");
        return 1;
    }

    // Write data to the file
    fprintf(filePointer, "%s\n", dataToWrite);
    fclose(filePointer);

    // Open the file for reading
    filePointer = fopen("example.txt", "r");
    if (filePointer == NULL) {
        printf("Failed to open the file.\n");
        return 1;
    }

    // Read data from the file
    fgets(dataRead, 50, filePointer);
    printf("Data read from file: %s", dataRead);
    fclose(filePointer);

    return 0;
}

Explanation

  1. Opening the File for Writing:

    filePointer = fopen("example.txt", "w");
    
    • Opens the file example.txt in write mode. If the file doesn't exist, it will be created.
  2. Writing to the File:

    fprintf(filePointer, "%s\n", dataToWrite);
    
    • Writes the string dataToWrite to the file.
  3. Closing the File:

    fclose(filePointer);
    
    • Closes the file, ensuring all data is written and resources are released.
  4. Opening the File for Reading:

    filePointer = fopen("example.txt", "r");
    
    • Opens the file example.txt in read mode.
  5. Reading from the File:

    fgets(dataRead, 50, filePointer);
    
    • Reads a string from the file into the dataRead buffer.
  6. Closing the File:

    fclose(filePointer);
    
    • Closes the file.

Practical Exercise

Exercise

  1. Create a program that:
    • Opens a file named data.txt in write mode.
    • Writes the numbers 1 to 10, each on a new line.
    • Closes the file.
    • Reopens the file in read mode.
    • Reads and prints each number from the file.

Solution

#include <stdio.h>

int main() {
    FILE *filePointer;
    int i, number;

    // Open the file for writing
    filePointer = fopen("data.txt", "w");
    if (filePointer == NULL) {
        printf("Failed to open the file.\n");
        return 1;
    }

    // Write numbers 1 to 10 to the file
    for (i = 1; i <= 10; i++) {
        fprintf(filePointer, "%d\n", i);
    }
    fclose(filePointer);

    // Open the file for reading
    filePointer = fopen("data.txt", "r");
    if (filePointer == NULL) {
        printf("Failed to open the file.\n");
        return 1;
    }

    // Read and print each number from the file
    while (fscanf(filePointer, "%d", &number) != EOF) {
        printf("%d\n", number);
    }
    fclose(filePointer);

    return 0;
}

Explanation

  1. Writing Numbers to the File:

    • The for loop writes numbers 1 to 10 to data.txt.
  2. Reading and Printing Numbers:

    • The while loop reads each number from the file and prints it until the end of the file is reached.

Conclusion

In this section, you learned the basics of file handling in C, including how to open, read, write, and close files. You also saw practical examples and exercises to reinforce these concepts. In the next section, we will delve deeper into reading and writing files with more advanced techniques.

© Copyright 2024. All rights reserved