File Handling in C Practice Questions with Solutions

Introduction

File handling in C allows a program to store data permanently in files instead of keeping it only in memory while the program is running. In this chapter, you will practice opening, creating, writing, reading, appending, and closing files using functions such as fopen(), fprintf(), fscanf(), fgetc(), fputc(), fgets(), fputs(), and fclose(). These examples start with simple programs and gradually introduce practical file operations. File Handling in C Practice questions with solutions to help you understand the concepts.

Q1. Create and Open a File in C

Problem Statement

Write a C program to create and open a file using fopen() and then close the file using fclose().

C Program

#include <stdio.h>

int main()
{
    FILE *file;

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

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

    printf("File opened successfully");

    fclose(file);

    return 0;
}

Sample Output

File opened successfully

Explanation

First, create a file pointer:

FILE *file;

FILE is the type used by the C standard library to represent a stream associated with a file.

Then:

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

opens data.txt in write mode.

If the file does not already exist, "w" mode normally creates it.

We check whether the file opened successfully:

if (file == NULL)

Finally, close the file:

fclose(file);

Closing a file is an important part of file handling.

Concepts Covered

  • FILE
  • fopen()
  • "w" mode
  • NULL
  • fclose()

Q2. Write Text to a File Using fprintf()

Problem Statement

Create a file named student.txt and write a student’s name, age, and marks into it using fprintf().

C Program

#include <stdio.h>

int main()
{
    FILE *file;

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

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

    fprintf(file, "Name: Rahul\n");
    fprintf(file, "Age: 18\n");
    fprintf(file, "Marks: 85.5\n");

    fclose(file);

    printf("Student data written successfully");

    return 0;
}

Sample Output

Student data written successfully

Content of student.txt

Name: Rahul
Age: 18
Marks: 85.5

Explanation

fprintf() works similarly to printf(), but instead of displaying the formatted output on the screen, it writes it to the specified file.

For example:

fprintf(file, "Age: 18\n");

Here:

  • file tells C where to write.
  • "Age: 18\n" is the text being written.

The file is opened using:

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

and closed using:

fclose(file);

Concepts Covered

  • fprintf()
  • File writing
  • Formatted output
  • File pointer
  • fclose()

Q3. Write a Character to a File Using fputc()

Problem Statement

Create a file and write the characters A, B, C, D, and E into it using fputc().

C Program

#include <stdio.h>

int main()
{
    FILE *file;

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

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

    fputc('A', file);
    fputc('B', file);
    fputc('C', file);
    fputc('D', file);
    fputc('E', file);

    fclose(file);

    printf("Characters written successfully");

    return 0;
}

Sample Output

Characters written successfully

Content of letters.txt

ABCDE

Explanation

fputc() writes one character to a file.

Syntax:

fputc(character, file_pointer);

For example:

fputc('A', file);

writes the character A into the file.

You can also use fputc() inside a loop when you need to write many characters.

Concepts Covered

  • fputc()
  • Character output
  • File pointer
  • Writing files

Q4. Write a String to a File Using fputs()

Problem Statement

Create a file and write three lines of text using fputs().

C Program

#include <stdio.h>

int main()
{
    FILE *file;

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

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

    fputs("Welcome to C Programming\n", file);
    fputs("File handling is useful.\n", file);
    fputs("Keep practicing C.\n", file);

    fclose(file);

    printf("Text written successfully");

    return 0;
}

Sample Output

Text written successfully

Content of message.txt

Welcome to C Programming
File handling is useful.
Keep practicing C.

Explanation

fputs() writes a string to a file.

Syntax:

fputs(string, file_pointer);

For example:

fputs("Hello\n", file);

writes the string Hello followed by a newline.

Unlike fprintf(), fputs() does not perform formatted output.

Concepts Covered

  • fputs()
  • Strings
  • File writing
  • Newline character

Q5. Read a Character from a File Using fgetc()

Problem Statement

Create a file containing text and then read the file character by character using fgetc().

C Program

#include <stdio.h>

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

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

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

    fputs("Hello C Programming", file);

    fclose(file);

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

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

    while ((ch = fgetc(file)) != EOF)
    {
        printf("%c", ch);
    }

    fclose(file);

    return 0;
}

Sample Output

Hello C Programming

Explanation

First, we create and write to the file.

Then we reopen it using:

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

"r" means read mode.

The important part is:

while ((ch = fgetc(file)) != EOF)

fgetc() reads one character at a time.

When the end of the file is reached, it returns EOF.

The variable is declared as:

int ch;

rather than char because fgetc() needs to be able to represent every possible character value as well as the special EOF value.

Concepts Covered

  • fgetc()
  • Reading files
  • EOF
  • Read mode
  • Character-by-character reading

Q6. Read a Line from a File Using fgets()

Problem Statement

Create a file containing multiple lines and read the file line by line using fgets().

C Program

#include <stdio.h>

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

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

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

    fputs("C is a programming language.\n", file);
    fputs("File handling is an important topic.\n", file);
    fputs("Practice makes programming easier.\n", file);

    fclose(file);

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

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

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

    fclose(file);

    return 0;
}

Sample Output

C is a programming language.
File handling is an important topic.
Practice makes programming easier.

Explanation

fgets() reads a line of text from a file.

Syntax:

fgets(buffer, size, file_pointer);

Here:

fgets(line, sizeof(line), file)

means:

  • line → where the text is stored
  • sizeof(line) → maximum buffer size
  • file → file from which the text is read

The loop continues while fgets() successfully reads a line.

Concepts Covered

  • fgets()
  • Reading lines
  • Character arrays
  • sizeof()
  • EOF-style loop termination through the function result

Q7. Read Formatted Data Using fscanf()

Problem Statement

Create a file containing a student’s name, age, and marks. Read the data from the file using fscanf().

C Program

#include <stdio.h>

int main()
{
    FILE *file;
    char name[50];
    int age;
    float marks;

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

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

    fprintf(file, "Rahul 18 85.5");

    fclose(file);

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

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

    fscanf(file, "%49s %d %f", name, &age, &marks);

    printf("Name = %s\n", name);
    printf("Age = %d\n", age);
    printf("Marks = %.2f\n", marks);

    fclose(file);

    return 0;
}

Sample Output

Name = Rahul
Age = 18
Marks = 85.50

Content of student.txt

Rahul 18 85.5

Explanation

fscanf() reads formatted data from a file.

This statement:

fscanf(file, "%49s %d %f", name, &amp;age, &amp;marks);

reads:

String → name
Integer → age
Float → marks

The 49 in %49s limits how many characters are read into name, leaving room for the terminating '\0' in the 50-character array.

fscanf() is useful when the file follows a predictable format.

Concepts Covered

  • fscanf()
  • Formatted file input
  • Strings
  • Integers
  • Floating-point values

Q8. Append Data to an Existing File

Problem Statement

Create a file with one line of text and then add another line at the end using append mode.

C Program

#include <stdio.h>

int main()
{
    FILE *file;

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

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

    fputs("Rahul\n", file);

    fclose(file);

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

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

    fputs("Aman\n", file);

    fclose(file);

    printf("Data appended successfully");

    return 0;
}

Sample Output

Data appended successfully

Content of students.txt

Rahul
Aman

Explanation

The first time, the file is opened in write mode:

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

Then we reopen it in append mode:

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

The "a" mode writes new data at the end of the existing file.

This means existing content is preserved.

For example, if the file contains:

Rahul

and we append:

Aman

the final file becomes:

Rahul
Aman

Concepts Covered

  • Append mode
  • "a"
  • fputs()
  • Preserving existing data
  • File writing

Q9. Count Characters in a File

Problem Statement

Read a file character by character and count how many characters it contains.

C Program

#include <stdio.h>

int main()
{
    FILE *file;
    int ch;
    int count = 0;

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

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

    fputs("Hello C", file);

    fclose(file);

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

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

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

    fclose(file);

    printf("Number of characters = %d", count);

    return 0;
}

Sample Output

Number of characters = 7

Explanation

The file contains:

Hello C

There are seven characters:

H e l l o _ C

The loop reads one character at a time:

while ((ch = fgetc(file)) != EOF)

For every successfully read character:

count++;

The final count is displayed.

Concepts Covered

  • fgetc()
  • EOF
  • Loops
  • Character counting
  • File reading

Q10. Create a Simple Student File Program

Problem Statement

Create a file containing the details of three students and then read and display all student records.

C Program

#include <stdio.h>

int main()
{
    FILE *file;
    char name[50];
    int age;
    float marks;
    int i;

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

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

    fprintf(file, "Rahul 18 85.5\n");
    fprintf(file, "Aman 17 91.0\n");
    fprintf(file, "Priya 19 88.5\n");

    fclose(file);

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

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

    printf("Student Records:\n\n");

    for (i = 1; i <= 3; i++)
    {
        if (fscanf(file, "%49s %d %f", name, &age, &marks) == 3)
        {
            printf("Student %d\n", i);
            printf("Name: %s\n", name);
            printf("Age: %d\n", age);
            printf("Marks: %.2f\n\n", marks);
        }
    }

    fclose(file);

    return 0;
}

Sample Output

Student Records:

Student 1
Name: Rahul
Age: 18
Marks: 85.50

Student 2
Name: Aman
Age: 17
Marks: 91.00

Student 3
Name: Priya
Age: 19
Marks: 88.50

Content of students.txt

Rahul 18 85.5
Aman 17 91.0
Priya 19 88.5

Explanation

First, we create the file and write three student records:

fprintf(file, "Rahul 18 85.5\n");

Then we reopen the file in read mode:

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

Inside the loop, fscanf() reads one complete record:

fscanf(file, "%49s %d %f", name, &amp;age, &amp;marks)

The return value is checked:

== 3

because we expect three successful conversions:

  1. Name
  2. Age
  3. Marks

This is a simple example of storing and retrieving structured text data using files.

Concepts Covered

  • fopen()
  • fprintf()
  • fscanf()
  • Reading and writing files
  • File modes
  • Loops
  • File-based records
  • fclose()

Key Takeaways

  • File handling allows C programs to store and retrieve data from files.
  • FILE * is used to work with C file streams.
  • fopen() opens a file.
  • fclose() closes a file.
  • "r" opens a file for reading.
  • "w" opens a file for writing and can truncate existing contents.
  • "a" opens a file for appending.
  • fprintf() writes formatted data.
  • fscanf() reads formatted data.
  • fputc() writes one character.
  • fgetc() reads one character.
  • fputs() writes a string.
  • fgets() reads a line or part of a line.
  • EOF indicates the end of an input stream when using functions such as fgetc().
  • Always check whether fopen() returned NULL.
  • Always close files after completing the required operations.

FAQs

1. What is file handling in C?

File handling is the process of creating, opening, reading, writing, appending, and closing files using C’s standard input/output functions.

2. What is fopen() in C?

fopen() opens a file and returns a pointer to a FILE object.

Example:

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

3. What is the difference between "w" and "a" file modes?

"w" opens a file for writing and can remove existing contents when the file already exists. "a" opens a file for appending, so new output is written at the end while existing contents are preserved.

4. What is fclose() used for?

fclose() closes an opened file stream after the program finishes working with it.

fclose(file);

5. What is the difference between fgetc() and fgets()?

fgetc() reads one character from a file, while fgets() reads a line or a portion of a line into a character array.

6. What is the difference between fprintf() and fputs()?

fprintf() supports formatted output such as integers and floating-point values. fputs() writes a string without formatted conversion.

7. Why does fopen() return NULL?

fopen() returns NULL when the requested file operation cannot be performed, such as when a file cannot be found in read mode or another file-opening error occurs.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top