In this section, we will explore how to handle file input and output (I/O) in C. File handling is a crucial part of many applications, allowing programs to read from and write to files, which is essential for data persistence.

Key Concepts

  1. File Pointers: Used to keep track of the current position in the file.
  2. File Modes: Different modes for opening files (e.g., read, write, append).
  3. Standard Library Functions: Functions provided by the C standard library for file operations.

File Pointers

A file pointer is a pointer of type FILE that is used to keep track of the current position in the file. It is declared as follows:

FILE *filePointer;

File Modes

When opening a file, you need to specify the mode in which the file should be opened. 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 reading and writing. The file must exist.
"w+" Open for reading and writing. Creates a new file if it doesn't exist or truncates the file if it does.
"a+" Open for reading and appending. Data is added to the end of the file.

Opening a File

To open a file, use the fopen function, which returns a file pointer:

FILE *filePointer = fopen("example.txt", "r");
if (filePointer == NULL) {
    printf("Error opening file.\n");
    return 1;
}

Reading from a File

To read from a file, you can use functions like fgetc, fgets, or fread.

Example: Reading a File Character by Character

FILE *filePointer = fopen("example.txt", "r");
if (filePointer == NULL) {
    printf("Error opening file.\n");
    return 1;
}

char ch;
while ((ch = fgetc(filePointer)) != EOF) {
    putchar(ch);
}

fclose(filePointer);

Example: Reading a File Line by Line

FILE *filePointer = fopen("example.txt", "r");
if (filePointer == NULL) {
    printf("Error opening file.\n");
    return 1;
}

char buffer[256];
while (fgets(buffer, sizeof(buffer), filePointer) != NULL) {
    printf("%s", buffer);
}

fclose(filePointer);

Writing to a File

To write to a file, you can use functions like fputc, fputs, or fwrite.

Example: Writing to a File Character by Character

FILE *filePointer = fopen("example.txt", "w");
if (filePointer == NULL) {
    printf("Error opening file.\n");
    return 1;
}

const char *text = "Hello, World!";
for (int i = 0; text[i] != '\0'; i++) {
    fputc(text[i], filePointer);
}

fclose(filePointer);

Example: Writing a String to a File

FILE *filePointer = fopen("example.txt", "w");
if (filePointer == NULL) {
    printf("Error opening file.\n");
    return 1;
}

const char *text = "Hello, World!";
fputs(text, filePointer);

fclose(filePointer);

Practical Exercise

Exercise: Copying a File

Write a program that copies the contents of one file to another.

Solution

#include <stdio.h>

int main() {
    FILE *sourceFile = fopen("source.txt", "r");
    if (sourceFile == NULL) {
        printf("Error opening source file.\n");
        return 1;
    }

    FILE *destinationFile = fopen("destination.txt", "w");
    if (destinationFile == NULL) {
        printf("Error opening destination file.\n");
        fclose(sourceFile);
        return 1;
    }

    char ch;
    while ((ch = fgetc(sourceFile)) != EOF) {
        fputc(ch, destinationFile);
    }

    fclose(sourceFile);
    fclose(destinationFile);

    printf("File copied successfully.\n");
    return 0;
}

Common Mistakes and Tips

  • Forgetting to Close Files: Always close files using fclose to free up resources.
  • Checking for NULL: Always check if the file pointer is NULL after attempting to open a file.
  • Buffer Sizes: Ensure buffer sizes are adequate to prevent overflow when reading lines.

Conclusion

In this section, we covered the basics of reading from and writing to files in C. We learned about file pointers, file modes, and the standard library functions used for file I/O. We also provided practical examples and an exercise to reinforce the concepts. In the next section, we will delve into file positioning and how to handle errors in file operations.

© Copyright 2024. All rights reserved