📚 C Programming Tutorial

C Programming

Learn C programming concepts with simple explanations, examples and practical notes.

← Back to C Programming

File

Introduction to file handling in C

A file is a collection of data stored on a secondary storage device, such as a hard disk or SSD. Unlike ordinary variables, whose values generally last only while a program is running, files can store data for later use.

Why do we need files?

  • To store data permanently.
  • To retrieve previously stored information.
  • To process large amounts of data.
  • To maintain records such as students, employees, products, and accounts.
  • To search and update stored information.

Types of files in C

  1. Text file: Stores data as characters, generally in a human-readable form.
    Example: students.txt
  2. Binary file: Stores data as bytes. The contents are not necessarily human-readable when opened in a text editor.
    Example: students.dat

File operations

There are different operations that can be carried out on a file. These are:
(a) Creation of a new file
(b) Opening an existing file
(c) Reading from a file
(d) Writing to a file
(e) Moving to a specific location in a file (seeking)
(f) Closing a file

File pointers in C

A file pointer is a pointer of type FILE * used to access and manage a file through the C standard I/O library.

The FILE type is declared in the header file <stdio.h>.

Syntax:

FILE *fp;

Here:
- FILE is a type used by the C standard I/O library to represent a stream.
- *fp declares a pointer to a FILE object.
- fp is used to refer to the stream opened by a file operation.

Opening a file

The fopen() function opens the file in the specified mode and returns a file pointer on success. If it fails, it returns NULL.

Syntax:

fp = fopen("filename", "mode");
Mode Meaning
Text file
"r" Open an existing file for reading
"w" Open for writing; create or truncate the file
"a" Open for appending; create if necessary
"r+" Open an existing file for reading and writing
"w+" Open for reading and writing; create or truncate
"a+" Open for reading and appending; create if necessary
Binary file
"rb" Open a binary stream for reading
"wb" Open a binary stream for writing
"ab" Open a binary stream for appending
"rb+" Open a binary stream for reading and writing
"wb+" Open a binary stream for reading and writing; truncate
"ab+" Open a binary stream for reading and appending

In fact fopen() performs two important tasks when you open the file in "r" mode:
(a) Firstly it searches on the disk the file to be opened; if the file is not found, it returns NULL.
(b) It sets up a character pointer that points to the first character to read.

In "w" mode:
(a) Firstly it searches on the disk the file to be opened; if it is not found, it creates a file with the given filename.
(b) It sets up a character pointer that points to the first character to write.

Always check whether the file opened successfully.

FILE *fp = fopen("students.txt", "r");

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

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

Closing a file

When we have finished all the operations on the file, we need to close it. This is done using the function fclose().

Syntax:

fclose(fp);

Writing and reading a file

Common file writing functions

Function Purpose Syntax
fputc() Writes one character fputc(character, file_pointer);
fputs() Writes a string fputs(string, file_pointer);
fprintf() Writes formatted text fprintf(file_pointer, "format_specifier", variables);
fwrite() Writes blocks of bytes fwrite(pointer, size, count, file_pointer);

Common file reading functions

Function Purpose Syntax
fgetc() Reads one character character = fgetc(file_pointer);
fgets() Reads a line or part of a line fgets(string, size, file_pointer);
fscanf() Reads formatted data fscanf(file_pointer, "format_specifier", &variables);
fread() Reads blocks of bytes fread(pointer, size, count, file_pointer);

Example: C Program to write one character

#include <stdio.h>

int main() {
    FILE *fp;

    fp = fopen("data.txt", "w");

    fputc('A', fp);

    fclose(fp);

    return 0;
}

Output in data.txt:

A

Example: C Program to read one character

#include <stdio.h>

int main() {
    FILE *fp;
    int ch;

    fp = fopen("data.txt", "r");

    if (fp == NULL) {
        printf("File cannot be opened");
        return 1;
    }

    ch = fgetc(fp);

    printf("Character = %c\n", ch);

    fclose(fp);

    return 0;
}

Output (if data.txt contains A):

Character = A

Example: C Program to write a string to a file

#include <stdio.h>

int main() {
    FILE *fp;

    fp = fopen("data.txt", "w");

    if (fp == NULL) {
        printf("File cannot be opened");
        return 1;
    }

    fputs("Hello World", fp);

    fclose(fp);

    return 0;
}

Output in data.txt:

Hello World

Example: C Program to read a string from a file

#include <stdio.h>

int main() {
    FILE *fp;
    char str[50];

    fp = fopen("data.txt", "r");

    if (fp == NULL) {
        printf("File cannot be opened");
        return 1;
    }

    if (fgets(str, sizeof(str), fp) != NULL) {
        printf("%s", str);
    }

    fclose(fp);

    return 0;
}

Output:

Hello World

Example: C Program to write formatted data to a file

#include <stdio.h>

int main() {
    FILE *fp;

    fp = fopen("data.txt", "w");

    if (fp == NULL) {
        printf("File cannot be opened");
        return 1;
    }

    int age = 20;
    float marks = 85.5;

    fprintf(fp, "Age = %d\n", age);
    fprintf(fp, "Marks = %.1f\n", marks);

    fclose(fp);

    return 0;
}

Output in data.txt:

Age = 20
Marks = 85.5

Example: C Program to read formatted data from a file

#include <stdio.h>

int main() {
    FILE *fp;
    int age;
    float marks;

    fp = fopen("data.txt", "r");

    if (fp == NULL) {
        printf("File cannot be opened");
        return 1;
    }

    if (fscanf(fp, "%d %f", &age, &marks) == 2) {
        printf("Age = %d\n", age);
        printf("Marks = %.1f\n", marks);
    }

    fclose(fp);

    return 0;
}

Output:

Age = 20
Marks = 85.5

Binary file example using structures

#include <stdio.h>

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

int main() {
    FILE *fp;
    struct Student s1 = {1, "Naveen"}, s2;

    // Writing structure to file
    fp = fopen("data.dat", "wb+");
    fwrite(&s1, sizeof(s1), 1, fp);

    // Move file pointer to the beginning
    rewind(fp);

    // Reading structure from file
    fread(&s2, sizeof(s2), 1, fp);
    fclose(fp);

    printf("ID: %d\n", s2.id);
    printf("Name: %s\n", s2.name);

    return 0;
}

Output:

ID: 1
Name: Naveen

rewind(fp) moves the file pointer to the beginning of the file. In this program, the file is opened in "wb+" mode, which is for both writing and reading data from a file