Opening, reading, writing, and closing files.

Lesson 7.1: Opening, Reading, Writing, and Closing Files


In this lesson, you'll learn how to interact with files, allowing your C programs to read data from existing files and write data to new or existing files. This opens up a wide range of possibilities for storing, retrieving, and processing information.


File Handling Basics


File Pointer:


In C, you work with files through a file pointer (FILE *).

This pointer acts as a reference to the file and is used in all file I/O operations.

fopen() Function:


The fopen() function is used to open a file.

It takes two arguments:

Filename: The name of the file you want to open (e.g., "data.txt").

Mode: Specifies how you want to access the file (e.g., read, write, append).

Common File Modes:


"r": Open for reading (file must exist).

"w": Open for writing (creates a new file or overwrites an existing one).

"a": Open for appending (adds data to the end of the file).

"r+": Open for both reading and writing (file must exist).

"w+": Open for both reading and writing (creates a new file or overwrites an existing one).

"a+": Open for both reading and appending (creates a new file if it doesn't exist).

fclose() Function:


The fclose() function is used to close a file after you're done with it.

It's important to close files to release system resources and ensure data integrity.

Reading from a File


fscanf() Function:

Reads formatted data from a file (similar to scanf() for console input).

C

FILE *file = fopen("data.txt", "r");

int num;

fscanf(file, "%d", &num);  // Read an integer from the file

fclose(file);

content_copy

fgets() Function:

Reads a line of text from a file.

C

char line[256];

fgets(line, sizeof(line), file); // Read a line into the 'line' array

fgetc() Function:

Reads a single character from a file.

C

int ch;

while ((ch = fgetc(file)) != EOF) { // EOF (End of File) is a special marker

    // Process the character

}

Writing to a File


fprintf() Function:

Writes formatted data to a file (similar to printf() for console output).

C

FILE *file = fopen("output.txt", "w"); // Create or overwrite the file

fprintf(file, "Hello, %s!\n", "World");

fclose(file);

fputs() Function:

Writes a string to a file.

C

fputs("This is a line of text.\n", file);

fputc() Function:

Writes a single character to a file.

C

fputc('A', file);

Example: Copying a File


C

#include <stdio.h>

#include <stdlib.h> // For exit()


int main() {

    FILE *sourceFile = fopen("input.txt", "r");

    FILE *destinationFile = fopen("output.txt", "w");


    if (sourceFile == NULL || destinationFile == NULL) {

        perror("Error opening files");

        exit(1); // Exit with error code

    }


    int ch;

    while ((ch = fgetc(sourceFile)) != EOF) {

        fputc(ch, destinationFile); // Copy each character

    }


    fclose(sourceFile);

    fclose(destinationFile);


    printf("File copied successfully!\n");

    return 0;

}

Key Points:


**FILE *: The file pointer.

fopen(): Opens a file.

File Modes: Specify how to access the file.

fclose(): Closes a file.

fscanf(), fgets(), fgetc(): Reading functions.

fprintf(), fputs(), fputc(): Writing functions.

Error Handling: Always check for errors when working with files (e.g., if a file doesn't exist or can't be opened).

Course Syllabus