Loading...
files

Here’s a detailed note on File Handling in C:


File Handling in C

1. Introduction

File handling allows programs to read, write, and manipulate data stored in files. It is essential for data persistence, as files retain data even after the program terminates.


2. File Operations

C provides several standard functions for file handling, which are defined in the <stdio.h> library.

OperationFunctionDescription
Opening a filefopenOpens a file in a specific mode.
Closing a filefcloseCloses an open file.
Reading from a filefgetc, fgets, freadReads data from a file.
Writing to a filefputc, fputs, fwriteWrites data to a file.
Repositioningfseek, ftellMoves the file pointer to a specific position.
Error handlingfeof, ferrorDetects end-of-file or errors.

3. File Modes

When opening a file, you specify a mode to determine its behavior.

ModeDescription
rOpens a file for reading.
wOpens a file for writing (creates or overwrites).
aOpens a file for appending.
r+Opens a file for reading and writing.
w+Opens a file for reading and writing (creates or overwrites).
a+Opens a file for reading and appending.

4. File Pointer

The FILE data type is used to manage file operations.

FILE *fp; // Declares a file pointer

5. Opening and Closing Files

Opening a File

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

Closing a File

fclose(fp);

6. Reading from a File

Using fgetc (Character-by-Character)

FILE *fp = fopen("file.txt", "r");
char ch;
while ((ch = fgetc(fp)) != EOF) {
    putchar(ch);
}
fclose(fp);

Using fgets (Line-by-Line)

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

Using fread (Block of Data)

struct Data {
    int id;
    char name[20];
};

FILE *fp = fopen("data.bin", "rb");
struct Data d;
fread(&d, sizeof(d), 1, fp);
printf("ID: %d, Name: %s\n", d.id, d.name);
fclose(fp);

7. Writing to a File

Using fputc (Character-by-Character)

FILE *fp = fopen("file.txt", "w");
fputc('A', fp);
fclose(fp);

Using fputs (String)

FILE *fp = fopen("file.txt", "w");
fputs("Hello, World!", fp);
fclose(fp);

Using fwrite (Block of Data)

struct Data {
    int id;
    char name[20];
};

FILE *fp = fopen("data.bin", "wb");
struct Data d = {1, "Alice"};
fwrite(&d, sizeof(d), 1, fp);
fclose(fp);

8. Repositioning the File Pointer

fseek

Moves the file pointer to a specific position.

fseek(fp, offset, SEEK_SET); // From the beginning
fseek(fp, offset, SEEK_CUR); // From the current position
fseek(fp, offset, SEEK_END); // From the end

ftell

Returns the current position of the file pointer.

long position = ftell(fp);

rewind

Resets the file pointer to the beginning.

rewind(fp);

9. Error Handling

Check for End-of-File

if (feof(fp)) {
    printf("End of file reached.\n");
}

Check for Errors

if (ferror(fp)) {
    printf("Error reading file.\n");
}

10. Example Program: Copying File Content

#include <stdio.h>

int main() {
    FILE *source, *destination;
    char ch;

    source = fopen("source.txt", "r");
    destination = fopen("destination.txt", "w");

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

    while ((ch = fgetc(source)) != EOF) {
        fputc(ch, destination);
    }

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

    fclose(source);
    fclose(destination);

    return 0;
}

11. Binary vs Text Files

  • Text Files: Data is stored in human-readable form.
  • Binary Files: Data is stored in binary format for efficient storage and processing.

12. Applications of File Handling

  1. Data storage and retrieval.
  2. Logging and debugging.
  3. File transfer and processing.
  4. Creating structured files (e.g., CSV, JSON).