C Programming

Chapter 11 – File Handling in C Language

Chapter 11 – File Handling in C Language

Introduction

In previous chapters, we worked with data stored in variables, arrays, structures, and other memory locations. However, data stored in memory is generally temporary. When a program ends, that data is no longer available through the program.

File handling allows a C program to store data in files so that it can be used later.

Files can be used to:

Store student records

Save program output

Read previously stored information

Maintain employee records

Store text and configuration data

Create simple data-management applications

In this chapter, you will learn about files, file pointers, opening and closing files, reading and writing text, appending data, character and formatted I/O, binary files, and common file-handling errors.

1. What is File Handling?

File handling is the process of creating, opening, reading, writing, updating, and closing files using a programming language.

In C, file handling is mainly provided through functions from the:

#include <stdio.h>

header file.

A typical file-handling process is:

Open File   ↓ Read / Write / Update   ↓ Close File

2. Why Do We Need Files?

Suppose a program stores:

int marks = 85;

The value is available while the program is running.

If we want to save the marks for future use, we can write them to a file.

For example:

student.txt

could contain:

Rahul 85

The information can then be read again when the program runs later.

3. Types of Files

C programs commonly work with two broad types of files:

1. Text Files

Text files store information in a human-readable form.

Examples:

students.txt notes.txt data.csv

2. Binary Files

Binary files store data in a binary representation. They are useful when working with structured data where preserving the in-memory representation or compact storage is appropriate.

Examples include files used for storing binary records.

4. File Pointer

C uses a special type called FILE to represent an open file stream.

A file pointer is declared as:

FILE *fp;

Here:

FILE is defined by <stdio.h>.

fp is a pointer to the file stream.

Example:

#include <stdio.h> int main() {    FILE *fp;    return 0; }

5. Opening a File

The fopen() function is used to open a file.

Syntax

FILE *fopen(const char *filename, const char *mode);

Example:

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

Here:

data.txt is the file name.

"r" specifies the opening mode.

6. File Opening Modes

Some commonly used modes are:

ModeMeaning
"r"Open an existing file for reading
"w"Open for writing; creates or truncates the file
"a"Open for appending; creates the file if needed
"r+"Open an existing file for reading and writing
"w+"Open for reading and writing; creates or truncates
"a+"Open for reading and appending; creates if needed

Binary versions can be used by adding b, such as:

"rb" "wb" "ab"

7. Opening a File for Writing

Example:

#include <stdio.h> int main() {    FILE *fp;    fp = fopen("data.txt", "w");    if(fp == NULL)    {        printf("Unable to open file.");        return 1;    }    printf("File opened successfully.");    fclose(fp);    return 0; }

If the file does not exist, "w" can create it.

Important: If the file already exists, "w" normally truncates its previous contents.

8. Closing a File

After finishing file operations, the file should be closed using:

fclose(fp);

Example:

FILE *fp; fp = fopen("data.txt", "w"); if(fp != NULL) {    /* File operations */    fclose(fp); }

Closing files helps release associated resources and ensures buffered output is properly handled.

9. Checking Whether a File Opened Successfully

fopen() can return NULL if the file could not be opened.

Therefore, always check the result when appropriate.

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

This is especially important when reading a file that may not exist.

10. Writing to a File Using fprintf()

The fprintf() function writes formatted data to a file.

Syntax

fprintf(file_pointer, "format", values);

Example:

#include <stdio.h> int main() {    FILE *fp;    fp = fopen("student.txt", "w");    if(fp == NULL)    {        printf("File could not be opened.");        return 1;    }    fprintf(fp, "Name: Rahul\n");    fprintf(fp, "Marks: 85\n");    fclose(fp);    return 0; }

The file may contain:

Name: Rahul Marks: 85

11. Writing Characters Using fputc()

The fputc() function writes one character to a file.

Syntax

fputc(character, file_pointer);

Example:

#include <stdio.h> int main() {    FILE *fp;    fp = fopen("data.txt", "w");    if(fp == NULL)    {        return 1;    }    fputc('A', fp);    fputc('B', fp);    fputc('C', fp);    fclose(fp);    return 0; }

The file will contain:

ABC

12. Writing Strings Using fputs()

The fputs() function writes a string to a file.

Example:

#include <stdio.h> int main() {    FILE *fp;    fp = fopen("message.txt", "w");    if(fp == NULL)    {        return 1;    }    fputs("Welcome to C Programming\n", fp);    fputs("File Handling Tutorial\n", fp);    fclose(fp);    return 0; }

13. Reading a Character Using fgetc()

The fgetc() function reads one character from a file.

Example:

#include <stdio.h> int main() {    FILE *fp;    int ch;    fp = fopen("data.txt", "r");    if(fp == NULL)    {        return 1;    }    ch = fgetc(fp);    if(ch != EOF)    {        printf("%c", ch);    }    fclose(fp);    return 0; }

14. Reading a File Character by Character

We can use a loop to read an entire file.

#include <stdio.h> int main() {    FILE *fp;    int ch;    fp = fopen("data.txt", "r");    if(fp == NULL)    {        printf("File could not be opened.");        return 1;    }    while((ch = fgetc(fp)) != EOF)    {        putchar(ch);    }    fclose(fp);    return 0; }

Here EOF represents the end-of-file condition returned by the input function.

15. Reading a Line Using fgets()

The fgets() function can read a line or a specified number of characters from a file.

Example:

#include <stdio.h> int main() {    FILE *fp;    char line[100];    fp = fopen("data.txt", "r");    if(fp == NULL)    {        return 1;    }    if(fgets(line, sizeof(line), fp) != NULL)    {        printf("%s", line);    }    fclose(fp);    return 0; }

fgets() is generally preferable to unsafe functions such as the old gets() function, which is not part of modern standard C.

16. Reading Formatted Data Using fscanf()

fscanf() works similarly to scanf(), but it reads formatted input from a file.

Example:

Suppose student.txt contains:

101 Rahul 85.5

Program:

#include <stdio.h> int main() {    FILE *fp;    int rollNo;    char name[50];    float marks;    fp = fopen("student.txt", "r");    if(fp == NULL)    {        return 1;    }    if(fscanf(fp, "%d %49s %f", &rollNo, name, &marks) == 3)    {        printf("Roll No: %d\n", rollNo);        printf("Name: %s\n", name);        printf("Marks: %.2f\n", marks);    }    fclose(fp);    return 0; }

17. Appending Data to a File

The "a" mode is used to append data to the end of a file.

Example:

#include <stdio.h> int main() {    FILE *fp;    fp = fopen("data.txt", "a");    if(fp == NULL)    {        return 1;    }    fprintf(fp, "\nNew information added.");    fclose(fp);    return 0; }

Existing contents are preserved, and new output is written at the end.

18. Difference Between "w" and "a"

This distinction is important.

"w"

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

Creates the file if it does not exist.

If it exists, its previous contents are discarded.

"a"

fopen("data.txt", "a");

Creates the file if it does not exist.

Preserves existing contents.

Adds new output at the end.

19. Reading and Writing with "r+"

The "r+" mode opens an existing file for both reading and writing.

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

The file must already exist.

It does not automatically erase the existing contents.

20. "w+" Mode

The "w+" mode allows reading and writing.

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

If the file does not exist, it is created.

If it already exists, its previous contents are discarded.

21. "a+" Mode

The "a+" mode allows both reading and appending.

FILE *fp = fopen("data.txt", "a+");

If the file does not exist, it can be created.

Writes are directed toward the end of the file.

22. Complete Write and Read Example

The following program first writes information to a file and then reads it.

#include <stdio.h> int main() {    FILE *fp;    int ch;    fp = fopen("sample.txt", "w");    if(fp == NULL)    {        printf("Unable to create file.");        return 1;    }    fprintf(fp, "C Language File Handling\n");    fprintf(fp, "This is a sample file.\n");    fclose(fp);    fp = fopen("sample.txt", "r");    if(fp == NULL)    {        printf("Unable to read file.");        return 1;    }    while((ch = fgetc(fp)) != EOF)    {        putchar(ch);    }    fclose(fp);    return 0; }

Output

C Language File Handling This is a sample file.

23. Binary Files

Binary files store data in a binary representation rather than as ordinary readable text.

C provides functions such as:

fread() fwrite()

for binary input and output.

Binary modes are commonly opened using:

"rb" "wb" "ab"

24. Writing Binary Data Using fwrite()

Example:

#include <stdio.h> struct Student {    int rollNo;    float marks; }; int main() {    FILE *fp;    struct Student student = {101, 88.5f};    fp = fopen("student.dat", "wb");    if(fp == NULL)    {        return 1;    }    fwrite(&student, sizeof(student), 1, fp);    fclose(fp);    return 0; }

The program writes the structure's object representation to the binary file.

25. Reading Binary Data Using fread()

Example:

#include <stdio.h> struct Student {    int rollNo;    float marks; }; int main() {    FILE *fp;    struct Student student;    fp = fopen("student.dat", "rb");    if(fp == NULL)    {        return 1;    }    if(fread(&student, sizeof(student), 1, fp) == 1)    {        printf("Roll No: %d\n", student.rollNo);        printf("Marks: %.2f\n", student.marks);    }    fclose(fp);    return 0; }

26. Important File Functions

FunctionPurpose
fopen()Opens a file
fclose()Closes a file
fprintf()Writes formatted data
fscanf()Reads formatted data
fputc()Writes one character
fgetc()Reads one character
fputs()Writes a string
fgets()Reads a line/string
fwrite()Writes binary data
fread()Reads binary data
fseek()Moves the file position
ftell()Gets the current file position
rewind()Moves position back to the beginning

27. File Position

C maintains a current position in an open file stream.

Functions such as:

ftell()

can be used to determine the current position.

Example:

long position = ftell(fp);

The returned value is measured relative to the beginning of the file for binary streams, with details depending on the stream and mode.

28. rewind()

The rewind() function moves the file position back to the beginning.

Example:

rewind(fp);

This can be useful when a program needs to read the file again from the beginning.

29. fseek()

The fseek() function changes the current file position.

Syntax

fseek(file_pointer, offset, origin);

Common origins include:

SEEK_SET SEEK_CUR SEEK_END

Example:

fseek(fp, 0, SEEK_SET);

This moves the position to the beginning of the file.

30. Error Handling

File operations can fail for many reasons:

File does not exist.

Permission is unavailable.

Path is incorrect.

Storage or system resources are unavailable.

Always check the return value of important file operations.

Example:

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

For more detailed error reporting, C programs can also use facilities such as perror().

31. Using perror()

The perror() function prints a message describing the most recent library/system error associated with certain operations.

Example:

#include <stdio.h> int main() {    FILE *fp;    fp = fopen("missing.txt", "r");    if(fp == NULL)    {        perror("Error");        return 1;    }    fclose(fp);    return 0; }

This can provide more useful diagnostic information than a custom message alone.

32. File Handling with Student Records

Structures and files can be combined to create useful applications.

Example:

#include <stdio.h> struct Student {    int rollNo;    char name[50];    float marks; }; int main() {    FILE *fp;    struct Student student = {101, "Aman", 89.5f};    fp = fopen("students.txt", "w");    if(fp == NULL)    {        printf("Unable to open file.");        return 1;    }    fprintf(fp, "%d %s %.2f\n",            student.rollNo,            student.name,            student.marks);    fclose(fp);    return 0; }

This approach can be extended to store multiple records.

33. Text File vs Binary File

FeatureText FileBinary File
Human-readableUsually yesUsually no
Data representationText charactersBinary representation
Common functionsfprintf(), fscanf(), fgets(), fputs()fread(), fwrite()
Editing manuallyEasierUsually more difficult
Typical extension.txt, .csv.dat, .bin

The choice depends on the application's requirements.

34. Standard Streams

C programs normally start with three standard streams:

StreamPurpose
stdinStandard input
stdoutStandard output
stderrStandard error output

For example:

printf("Hello");

writes to standard output.

And:

fprintf(stderr, "An error occurred.");

writes to the standard error stream.

35. Best Practices for File Handling

When working with files:

Always check whether fopen() succeeded.

Close files with fclose() when finished.

Choose the correct file mode.

Be careful with "w" because it can truncate an existing file.

Check return values of important input/output operations.

Use suitable buffer sizes with functions such as fgets().

Do not read beyond the available storage.

Handle errors appropriately.

Use text or binary files according to the application's needs.

36. Common Mistakes

Mistake 1: Forgetting to include <stdio.h>

File functions such as fopen() and fclose() are declared in <stdio.h>.

Mistake 2: Not checking fopen()

Incorrect:

FILE *fp = fopen("data.txt", "r"); fprintf(fp, "Hello");

If opening fails, fp may be NULL.

Better:

FILE *fp = fopen("data.txt", "r"); if(fp == NULL) {    return 1; }

Mistake 3: Forgetting to close the file

Always close an opened file when the program has finished using it.

fclose(fp);

Mistake 4: Using "w" unintentionally

Opening an existing file with "w" can erase its previous contents.

Use "a" when the goal is to add data to the end.

Mistake 5: Confusing EOF with a character

fgetc() returns an int, not simply a char, because it must be able to represent every possible unsigned character value as well as EOF.

Therefore, use:

int ch;

when reading characters with fgetc().

37. Mini Project – Student Record File

The following example stores several student records in a text file.

#include <stdio.h> struct Student {    int rollNo;    char name[50];    float marks; }; int main() {    FILE *fp;    struct Student students[3] =    {        {101, "Aman", 85.5f},        {102, "Riya", 91.0f},        {103, "Karan", 78.5f}    };    int i;    fp = fopen("students.txt", "w");    if(fp == NULL)    {        printf("Unable to open file.");        return 1;    }    for(i = 0; i < 3; i++)    {        fprintf(fp, "%d %s %.2f\n",                students[i].rollNo,                students[i].name,                students[i].marks);    }    fclose(fp);    printf("Student records saved successfully.");    return 0; }

This demonstrates how structures, arrays, loops, and file handling can work together.

38. Quick Revision Table

ConceptMeaning
FilePersistent storage for data
FILE *Pointer to a file stream
fopen()Opens a file
fclose()Closes a file
"r"Read
"w"Write/create or truncate
"a"Append
fprintf()Formatted file output
fscanf()Formatted file input
fputc()Write a character
fgetc()Read a character
fputs()Write a string
fgets()Read a line/string
fread()Read binary data
fwrite()Write binary data
EOFEnd-of-file indicator
fseek()Change file position
ftell()Get current file position
rewind()Move to beginning

39. Practice MCQs

Question 1

Which header file provides standard C file-handling functions?

A. <stdlib.h>
B. <string.h>
C. <stdio.h>
D. <file.h>

Answer: C. <stdio.h>

Question 2

Which function is used to open a file?

A. openfile()
B. fopen()
C. fileopen()
D. open()

Answer: B. fopen()

Question 3

Which function closes a file?

A. close()
B. endfile()
C. fclose()
D. stopfile()

Answer: C. fclose()

Question 4

Which mode is normally used to open a file for reading?

A. "r"
B. "w"
C. "a"
D. "x"

Answer: A. "r"

Question 5

Which mode can truncate an existing file?

A. "r"
B. "a"
C. "w"
D. "r+"

Answer: C. "w"

Question 6

Which function writes formatted data to a file?

A. printf()
B. fprintf()
C. fprint()
D. writef()

Answer: B. fprintf()

Question 7

Which function reads one character from a file?

A. fgetc()
B. freadchar()
C. getcharfile()
D. readc()

Answer: A. fgetc()

Question 8

Which function writes a string to a file?

A. fwrite()
B. fputs()
C. putstring()
D. writes()

Answer: B. fputs()

Question 9

Which function is commonly used to read binary data?

A. fread()
B. fscanf()
C. fgets()
D. fgetc()

Answer: A. fread()

Question 10

What does EOF represent?

A. End of Function
B. End of File
C. Error on File
D. Empty Output File

Answer: B. End of File

40. Programming Exercises

Try writing C programs to:

Create a text file and write a message into it.

Read and display the contents of a text file.

Count the number of characters in a file.

Count the number of lines in a file.

Count the number of words in a text file.

Append new information to an existing file.

Store student details in a text file.

Read student details from a file.

Copy the contents of one text file into another.

Store employee records using structures and files.

Write and read a structure using fwrite() and fread().

Create a simple student-record application using file handling.

41. Key Points to Remember

File handling allows data to be stored beyond the execution of a program.

FILE * is used to work with file streams.

fopen() opens a file.

fclose() closes a file.

"r" is used for reading.

"w" is used for writing and can truncate an existing file.

"a" is used to append data.

fprintf() and fscanf() perform formatted file I/O.

fputc() and fgetc() work with individual characters.

fputs() and fgets() work with strings/lines.

fread() and fwrite() are commonly used for binary I/O.

Always check whether a file was successfully opened.

Always close files after completing the required operations.

fseek(), ftell(), and rewind() are useful for controlling file position.

Chapter Summary

File handling allows C programs to store and retrieve information from external files. Instead of keeping all information only in memory during program execution, a program can save data in text or binary files and use it later.

The most important functions include fopen(), fclose(), fprintf(), fscanf(), fputc(), fgetc(), fputs(), fgets(), fread(), and fwrite().

File handling becomes especially powerful when combined with structures, arrays, functions, and pointers, allowing programmers to create applications such as student-record systems, employee databases, and simple data-management programs.

Next Chapter

Chapter 12 – Dynamic Memory Allocation in C Language

In the next chapter, you will learn how C programs can allocate and release memory during runtime using malloc(), calloc(), realloc(), and free().