Lesson 53 of 60 – File Handling in C
88%

File Handling in C

File handling in C allows a program to create, open, read, write, append, and close files. Files are useful when data needs to be stored permanently instead of keeping it only in memory while the program is running.

Note: Most C file-handling functions are declared in the <stdio.h> header file. A file is generally accessed through a FILE * stream.

1. What is File Handling?

File handling means working with files from a C program. A program can use files to store and retrieve data.

Common file operations include:

  • Creating a file
  • Opening a file
  • Reading data
  • Writing data
  • Appending data
  • Closing a file

2. Why Use Files?

Variables normally store data only while the program is running. A file can store information so it can be used later.

For example, a student management program can store student information in a file.

3. stdio.h Header File

File handling functions are available through the standard input/output header file.

#include <stdio.h>

Functions such as fopen(), fclose(), fprintf(), fscanf(), fgets(), and fputs() are declared in this header.

4. FILE Pointer

C uses a FILE * pointer to work with an opened file stream.

FILE *file;

The pointer is used with functions such as fopen() and fclose().

5. fopen() Function

The fopen() function opens a file and returns a FILE * pointer.

FILE *file;

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

The first argument is the file name and the second argument specifies the opening mode.

6. fopen() Syntax

The general syntax is:

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

Example:

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

7. Checking fopen() Failure

Always check whether the file was opened successfully.

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

if(file == NULL)
{
    printf("Unable to open file");
}
else
{
    printf("File opened successfully");
}

A NULL return indicates that the file could not be opened.

8. File Opening Modes

Common text-file opening modes include:

Mode Purpose
"r" Open for reading
"w" Open for writing; create or truncate the file
"a" Open for appending; create if necessary
"r+" Open for reading and writing
"w+" Open for reading and writing; create or truncate
"a+" Open for reading and appending; create if necessary

9. Reading Mode "r"

The "r" mode opens an existing file for reading.

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

If the file does not exist, opening with "r" fails.

10. Writing Mode "w"

The "w" mode opens a file for writing. If the file does not exist, it can be created. If it already exists, its previous contents are discarded.

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

Use this mode carefully when existing data must be preserved.

11. Append Mode "a"

The "a" mode opens a file for appending. New data is written at the end of the file.

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

Existing contents are preserved.

12. fclose() Function

The fclose() function closes an opened file.

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

if(file != NULL)
{
    fclose(file);
}

Closing files is an important part of proper file handling.

13. Writing with fprintf()

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

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

if(file != NULL)
{
    fprintf(file, "Hello C Programming");

    fclose(file);
}

14. Writing Multiple Values

FILE *file = fopen("student.txt", "w");

if(file != NULL)
{
    int id = 101;
    float marks = 85.5f;

    fprintf(file, "ID: %d\n", id);
    fprintf(file, "Marks: %.2f\n", marks);

    fclose(file);
}

Formatted output can be stored in the file just like output with printf().

15. Reading with fscanf()

The fscanf() function reads formatted data from a file.

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

int number;

if(file != NULL)
{
    fscanf(file, "%d", &number);

    printf("%d", number);

    fclose(file);
}

16. Writing with fputs()

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

FILE *file = fopen("message.txt", "w");

if(file != NULL)
{
    fputs("Welcome to C Programming", file);

    fclose(file);
}

17. Reading with fgets()

The fgets() function can read a line or part of a line from a file into a character array.

char line[100];

FILE *file = fopen("message.txt", "r");

if(file != NULL)
{
    fgets(line, sizeof line, file);

    printf("%s", line);

    fclose(file);
}

18. Reading a File Line by Line

A loop can be used with fgets() to read a text file line by line.

char line[100];

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

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

    fclose(file);
}

19. fgetc() Function

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

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

if(file != NULL)
{
    int ch = fgetc(file);

    if(ch != EOF)
    {
        printf("%c", ch);
    }

    fclose(file);
}

An int is commonly used to store the result so that the special value EOF can also be represented.

20. Reading Characters Until EOF

The EOF indicator can be used to detect the end of a file while reading characters.

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

if(file != NULL)
{
    int ch;

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

    fclose(file);
}

21. fputc() Function

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

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

if(file != NULL)
{
    fputc('A', file);
    fputc('B', file);
    fputc('C', file);

    fclose(file);
}

The file will contain the characters ABC.

22. Text Files and Binary Files

Files are commonly handled as text or binary data.

  • Text files: Store data in a text-oriented representation.
  • Binary files: Store data as raw bytes.

C provides different functions and modes for working with these types of files.

23. Binary File Mode

The character b can be added to file modes for binary file operations.

FILE *file = fopen("data.bin", "rb");

Other examples include "wb" and "ab".

24. fwrite() Function

The fwrite() function writes blocks of bytes to a file. It is commonly used with binary data.

int numbers[3] = {10, 20, 30};

FILE *file = fopen("numbers.bin", "wb");

if(file != NULL)
{
    fwrite(numbers, sizeof numbers[0], 3, file);

    fclose(file);
}

25. fread() Function

The fread() function reads blocks of bytes from a file.

int numbers[3];

FILE *file = fopen("numbers.bin", "rb");

if(file != NULL)
{
    fread(numbers, sizeof numbers[0], 3, file);

    fclose(file);
}

26. File Position and rewind()

A file stream maintains a current position. The rewind() function moves the file position back to the beginning of the file.

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

if(file != NULL)
{
    char line[100];

    fgets(line, sizeof line, file);

    rewind(file);

    fgets(line, sizeof line, file);

    fclose(file);
}

27. Complete File Writing Program

#include <stdio.h>

int main()
{
    FILE *file;

    file = fopen("students.txt", "w");

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

    fprintf(file, "Student Management System\n");
    fprintf(file, "ID: 101\n");
    fprintf(file, "Name: Rahul\n");
    fprintf(file, "Marks: 85.50\n");

    fclose(file);

    printf("Data written successfully");

    return 0;
}

28. Complete File Reading Program

#include <stdio.h>

int main()
{
    FILE *file;
    char line[200];

    file = fopen("students.txt", "r");

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

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

    fclose(file);

    return 0;
}

29. Common File Handling Mistakes

  • Not checking whether fopen() returned NULL.
  • Using the wrong file mode.
  • Forgetting to close an opened file.
  • Reading data without checking the result.
  • Using an incorrect format specifier.
  • Writing to a file opened only for reading.
  • Accidentally truncating a file with "w".
  • Using a file pointer after the file has been closed.
  • Ignoring possible I/O errors.

30. Practice Project

Create a simple Student Record File Management program.

  1. Create a menu using switch.
  2. Add a student record to a text file.
  3. Store student ID, name, and marks.
  4. Display all student records.
  5. Use append mode to add new records.
  6. Use read mode to display saved records.
  7. Check every fopen() call for failure.
  8. Close the file after each operation.

This project combines file handling with structures, functions, conditions, loops, and formatted input/output.

📌 Key Points

  • File handling allows programs to store data permanently.
  • 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 for appending.
  • fprintf() writes formatted data.
  • fscanf() reads formatted data.
  • fputs() writes strings.
  • fgets() reads strings or lines.
  • fgetc() reads a character.
  • fputc() writes a character.
  • fread() and fwrite() are useful for binary data.
  • Always check whether a file was opened successfully.
  • Close files when they are no longer needed.

🧠 Quick Quiz

Question: Which function is used to open a file in C?