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.

Reading Functions in File Handling in C

Different file-reading functions solve different problems. `fgetc()` reads one character at a time, which is useful for character-driven parsing or when you want tight control over each byte. `fgets()` reads a whole line or up to a chosen buffer size, which makes it a safer and more practical option for many text-file tasks. `fscanf()` reads formatted input, which can be convenient when the file layout is structured, but it must be used carefully because badly matched formats can produce confusing bugs.

In practice, many beginners overuse `fscanf()` because it looks similar to `scanf()`. The problem is that file content is often messy, may contain spaces, or may not match the expected format perfectly. For line-oriented text processing, `fgets()` is usually easier to reason about because it lets the program read the input first and parse it afterward. That separation often produces safer code and makes debugging easier.

FunctionBest UseWhy It Helps
fgetc()Read one characterUseful for character-by-character logic
fgets()Read a line of textSafer for many text file tasks
fscanf()Read formatted fieldsWorks well when the file format is predictable
fread()Read binary dataUseful for raw bytes and structures

Append, Update, and EOF Handling in C

File modes such as `a`, `a+`, `r+`, and `w+` become important once a program needs more than simple one-time reading or overwriting. Append modes keep existing content and add new data at the end of the file, which is useful in logs and records. Update modes allow both reading and writing, but they should be chosen carefully because `w+` clears old content while `r+` expects the file to already exist. Understanding the exact behavior of each mode prevents accidental data loss.

End-of-file handling is another important concept. Reading functions usually signal that no more data is available through their return value. A correct program checks the return value of `fgets()`, `fgetc()`, `fscanf()`, `fread()`, or whichever function is being used instead of assuming data will always be present. This habit matters because robust file handling depends on checking what actually happened, not what the program hoped would happen.

int ch;

while ((ch = fgetc(fp)) != EOF)
{
    putchar(ch);
} c

This pattern works because the loop tests the return value directly. The program stops when `EOF` is reached instead of reading past the available content. Small patterns like this are part of what makes file handling reliable in real C programs.

File Management Functions in C

C also provides file-management functions beyond normal reading and writing. For example, `remove()` can delete a file and `rename()` can change a file name. These functions are useful in workflows such as rotating logs, replacing temporary files with final files, or cleaning up generated output after the program finishes. File handling is therefore not only about opening and reading. It also includes controlling the lifecycle of files used by the program.

if (rename("old.txt", "new.txt") != 0)
{
    printf("Rename failed\n");
} c

These operations should still be checked carefully because they can fail due to missing files, permissions, or path issues. As with `fopen()`, return-value checking remains one of the most important habits in all file-related code.

A Strong Error Handling Pattern for File Work

Good file handling code usually follows a repeatable pattern: open the file, verify the pointer, perform the intended operation, check the return values of read or write functions, and close the file before the function exits. If the operation is important, the program should also communicate what went wrong when a failure happens. Silent file failures are difficult to debug because the program may appear to run while producing incomplete or incorrect output.

This is one reason file handling is such a valuable topic in C. It teaches practical defensive programming. The program is dealing with the operating system, disk state, file permissions, and data outside its own memory. That environment is less predictable than ordinary arithmetic or variable assignments, so careful checks become part of normal professional style rather than optional extras.

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.


Continue learning C in order
Follow the topic sequence with the previous and next lesson.