C Programming

Unit 10: Files and File Handling in C

File concepts, opening modes, I/O functions, and sequential and random access.

Introduction and importance of files

A file is a collection of related data stored permanently in secondary storage. File handling is required when:

  • Data must be stored permanently beyond program execution.
  • Large amounts of data are involved.
  • The same data must be reused later.

In C, file handling is performed using a structure called FILE declared in <stdio.h>. A pointer of type FILE * is used to refer to a file.

Opening and closing a file

A file is opened using the fopen() function and closed using the fclose() function.

FILE *fp;
fp = fopen("data.txt", "w");   /* open for writing */

if (fp == NULL) {
    printf("Could not open file\n");
    return 1;
}

/* ... use the file ... */

fclose(fp);                    /* always close the file */

File opening modes

ModeMeaning
"r"Open an existing file for reading.
"w"Open a file for writing; creates a new file or overwrites existing one.
"a"Open a file for appending; creates a new file if it does not exist.
"r+"Open for both reading and writing (file must exist).
"w+"Open for reading and writing; truncates or creates the file.
"a+"Open for reading and appending.

Binary mode is indicated by adding b (e.g., "rb", "wb").

Input/output functions

C provides several functions to read from and write to files.

FunctionPurpose
fputcWrites a single character.
fgetcReads a single character.
fputsWrites a string.
fgetsReads a string.
fprintfWrites formatted output to a file.
fscanfReads formatted input from a file.
fwriteWrites binary data.
freadReads binary data.

Example — writing to a file:

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("data.txt", "w");
    if (fp == NULL) {
        printf("Cannot open file\n");
        return 1;
    }

    fprintf(fp, "Name: %s\n", "Ram");
    fprintf(fp, "Age : %d\n", 20);

    fclose(fp);
    return 0;
}

Example — reading from a file:

#include <stdio.h>

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

    if (fp == NULL) {
        printf("Cannot open file\n");
        return 1;
    }

    while (fgets(line, sizeof(line), fp) != NULL)
        printf("%s", line);

    fclose(fp);
    return 0;
}

Sequential access in file

In sequential access, data is read or written in the order in which it appears in the file. To access the 10th record, the previous 9 records must be processed first.

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("numbers.txt", "w");
    for (int i = 1; i <= 5; i++)
        fprintf(fp, "%d\n", i);
    fclose(fp);

    int n;
    fp = fopen("numbers.txt", "r");
    while (fscanf(fp, "%d", &n) == 1)
        printf("%d ", n);
    fclose(fp);
    return 0;
}

Random access in file

In random access, any record can be read or written directly without going through the previous records. C provides the following functions for random access:

FunctionPurpose
fseek(fp, offset, origin)Moves the file pointer to a desired position.
ftell(fp)Returns the current position of the file pointer.
rewind(fp)Moves the file pointer to the beginning of the file.

Possible values for origin in fseek:

  • SEEK_SET — beginning of file.
  • SEEK_CUR — current position.
  • SEEK_END — end of file.

Example — random access using fseek:

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("data.txt", "w+");
    fputs("ABCDEFGHIJ", fp);

    fseek(fp, 4, SEEK_SET);    /* move to 5th character */
    printf("Character: %c\n", fgetc(fp));   /* E */

    rewind(fp);                /* back to start         */
    printf("Character: %c\n", fgetc(fp));   /* A */

    fclose(fp);
    return 0;
}