File Handling in C

File handling in C is used when a program needs to save data permanently or read stored data later. Normal variables keep values only while the program is running. Once the program ends, that data is usually lost. Files solve this problem by allowing data to be written to disk and used again whenever the program is executed.

This is why file handling is one of the most practical topics in C. It is used in logs, reports, student records, configuration files, simple databases, and system utilities. In this article, we will understand file handling in C, file pointer, file modes, reading, writing, binary operations, file position functions, common mistakes, and best practices.

What is File Handling in C?

File handling in C is the process of creating, opening, reading, writing, updating, and closing files using functions from the standard library.

Instead of keeping all data only in RAM, a program can store it in a file and use it later.

File handling in C allows a program to work with permanent data stored outside the program.

Header File and FILE Pointer in C

File handling functions are provided through the stdio.h header file.

#include <stdio.h>

FILE *fp;

The pointer fp is used to refer to an opened file. Almost every file operation works through a FILE *.

Basic Steps of File Handling in C

  • Declare a file pointer
  • Open the file using fopen()
  • Read from or write to the file
  • Close the file using fclose()

Opening a File in C

A file is opened using fopen().

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

If the file cannot be opened, fopen() returns NULL.

fp = fopen("data.txt", "r");
if (fp == NULL)
{
    printf("File could not be opened\n");
    return 1;
}

File Modes in C

ModeMeaning
"r"Read existing file
"w"Write new file or overwrite existing file
"a"Append data at the end
"r+"Read and write
"w+"Read and write, but overwrite existing content
"a+"Read and append
"rb", "wb"Binary modes

Writing to a File in C

Formatted text is commonly written using fprintf(). Strings can also be written using fputs(), and characters using fputc().

#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("data.txt", "w");
    if (fp == NULL)
    {
        printf("File could not be opened\n");
        return 1;
    }

    fprintf(fp, "Name: Shreyas\n");
    fprintf(fp, "Marks: 92\n");

    fclose(fp);
    return 0;
}

This creates or overwrites the file and writes text into it.

Reading from a File in C

Reading can be done using fscanf(), fgets(), or fgetc(). For text lines, fgets() is often a safer choice.

#include <stdio.h>

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

    if (fp == NULL)
    {
        printf("File could not be opened\n");
        return 1;
    }

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

    fclose(fp);
    return 0;
}

Important File Functions in C

FunctionUse
fopen()Open a file
fclose()Close a file
fprintf()Write formatted data
fscanf()Read formatted data
fgets()Read a line or string
fputs()Write a string
fread()Read binary data
fwrite()Write binary data
fseek(), ftell(), rewind()Control file position

Binary File Handling in C

When data should be written exactly in byte form, binary operations are used. These are common for structures, images, and compact record storage.

#include <stdio.h>

struct Student
{
    int roll;
    float marks;
};

int main(void)
{
    FILE *fp;
    struct Student s1 = {101, 88.5f};

    fp = fopen("student.dat", "wb");
    if (fp == NULL)
    {
        printf("File could not be opened\n");
        return 1;
    }

    fwrite(&s1, sizeof(struct Student), 1, fp);
    fclose(fp);
    return 0;
}

For binary reading, fread() is used in a similar way.

Text File vs Binary File in C

PointText FileBinary File
Storage formReadable charactersRaw bytes
Human readabilityUsually readableUsually not readable
Main functionsfprintf(), fscanf(), fgets()fread(), fwrite()
Use caseReports, logs, configsRecords and structured binary data

File Position Functions in C

C also supports random access using file position functions.

  • fseek() moves the file position
  • ftell() returns the current position
  • rewind() moves back to the beginning

These functions are especially useful in binary files and larger data-processing programs.

Closing a File in C

After finishing file operations, always close the file using fclose().

fclose(fp);

This releases system resources and ensures buffered data is written properly.

Common Mistakes in File Handling in C

  • not checking whether fopen() returned NULL
  • using the wrong file mode
  • forgetting to close the file
  • confusing text and binary operations
  • reading without checking the return value of the read function
MistakeProblemBetter Practice
No NULL check after fopen()Program may fail badlyAlways verify file opened successfully
Using "w" by mistakeExisting content may be erasedChoose mode carefully
Forgetting fclose()Data may not flush properlyClose the file after use

Best Practices for File Handling in C

  • Always check whether the file opened successfully.
  • Use the correct file mode for the job.
  • Close the file in every successful path.
  • Prefer safe text-reading functions like fgets() where suitable.
  • Use binary functions only when raw byte storage is truly needed.

FAQs

What is file handling in C?

File handling in C is the process of opening, reading, writing, and closing files using standard library functions.

What is the use of FILE pointer in C?

A FILE * points to an opened file and is used by file handling functions to manage the file stream.

What is the difference between text and binary file in C?

Text files store readable characters, while binary files store raw byte data exactly as it exists in memory.

Why should fopen() be checked against NULL?

Because if the file cannot be opened, the pointer becomes NULL, and using it without checking can lead to errors.

Which function is used to close a file in C?

The fclose() function is used to close a file in C.

Which functions are used for binary file handling in C?

fread() and fwrite() are the main functions used for binary file handling in C.