C Files

File handling is an essential aspect of programming that allows you to create, read, write, and manipulate files. In C, file operations are performed using a powerful set of functions provided by the standard library.

In this guide by The Coding College, we’ll explore how to use C for file handling, including creating files, reading from files, and writing to files. This knowledge is vital for building applications that involve data storage and retrieval.

Why Use Files in C?

Using files allows data to persist even after the program has ended. Some common reasons for working with files include:

  • Storing large volumes of data.
  • Retaining logs or records.
  • Reading configurations for applications.

Types of File Access in C

  1. Text Files: Store data in a human-readable format, such as .txt files.
  2. Binary Files: Store data in a machine-readable format, which is more efficient for processing.

Working with Files in C

To handle files in C, you need to use the FILE type provided in the <stdio.h> library.

File Functions

Here are the most common functions used for file handling:

FunctionPurpose
fopen()Opens a file
fclose()Closes a file
fprintf()Writes formatted data to a file
fscanf()Reads formatted data from a file
fgets()Reads a string from a file
fputs()Writes a string to a file

1. Opening a File: fopen()

The fopen() function opens a file in a specified mode.

Syntax:

FILE *fopen(const char *filename, const char *mode);

Modes:

  • "r": Opens a file for reading.
  • "w": Opens a file for writing. If the file exists, it’s overwritten.
  • "a": Opens a file for appending.
  • "r+", "w+", "a+": Opens files for both reading and writing.

Example:

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");  // Open for writing
    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    printf("File opened successfully.\n");
    fclose(file);  // Close the file
    return 0;
}

Output:

File opened successfully.

2. Writing to a File: fprintf()

The fprintf() function writes formatted output to a file.

Example:

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    fprintf(file, "Welcome to The Coding College!\n");
    fclose(file);
    printf("Data written successfully.\n");
    return 0;
}

Output in example.txt:

Welcome to The Coding College!

3. Reading from a File: fgets()

The fgets() function reads a line from a file.

Example:

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    char line[100];

    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    while (fgets(line, sizeof(line), file)) {
        printf("%s", line);
    }
    fclose(file);
    return 0;
}

Output:

Welcome to The Coding College!

4. Appending Data to a File: fputs()

The fputs() function writes a string to a file in append mode.

Example:

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "a");
    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    fputs("This line is appended.\n", file);
    fclose(file);
    return 0;
}

Updated example.txt:

Welcome to The Coding College!
This line is appended.

5. Closing a File: fclose()

The fclose() function closes an open file. It’s important to close files to free system resources and avoid data corruption.

Handling Errors in File Operations

Always check the return value of file functions like fopen(). If the function returns NULL, it indicates an error.

Example:

FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL) {
    printf("Error: File does not exist.\n");
}

Practical Application: Student Records

Here’s an example that demonstrates file handling for storing and retrieving student records.

Code Example:

#include <stdio.h>

struct Student {
    char name[50];
    int age;
    float grade;
};

int main() {
    FILE *file = fopen("students.txt", "w");
    struct Student s1 = {"John Doe", 20, 85.5};

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

    fprintf(file, "Name: %s, Age: %d, Grade: %.2f\n", s1.name, s1.age, s1.grade);
    fclose(file);

    file = fopen("students.txt", "r");
    char line[100];
    while (fgets(line, sizeof(line), file)) {
        printf("%s", line);
    }
    fclose(file);

    return 0;
}

Output:

Name: John Doe, Age: 20, Grade: 85.50

Key Benefits of File Handling

  1. Data Persistence: Store data for future use.
  2. Efficiency: Handle large datasets without using memory.
  3. Data Sharing: Files are portable and can be shared across systems.

Conclusion

Mastering file handling in C is crucial for developing robust applications. It enables you to create, read, and manage data efficiently, laying the foundation for advanced programming tasks.

Leave a Comment