File Handling Practice in C Practice Questions with Solutions

Introduction

File handling becomes easier when you practice real programs instead of only learning functions. In this chapter, you will solve practical C programs involving student records, counting characters and words, copying files, searching text, calculating totals, and appending information. These examples combine fopen(), fprintf(), fscanf(), fgetc(), fgets(), fputs(), EOF, and fclose() so you can build confidence with file-based programs. File Handling Practice in C practice questions with solutions to help you understand the concepts.

Q1. Count the Number of Characters in a File

Problem Statement

Write a C program to create a file, store some text in it, and count the total number of characters.

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 Programming", 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("Total characters = %d", count);

    return 0;
}

Sample Output

Total characters = 19

Explanation

The program first writes:

Hello C Programming

to data.txt.

Then it opens the file in read mode:

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

fgetc() reads one character at a time:

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

Every time a character is successfully read, count increases:

count++;

The spaces are also counted as characters.

Concepts Covered

  • fopen()
  • fputs()
  • fgetc()
  • EOF
  • Character counting
  • fclose()

Q2. Count the Number of Lines in a File

Problem Statement

Create a file containing multiple lines and count how many lines it contains.

C Program

#include <stdio.h>

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

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

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

    fputs("C Programming\n", file);
    fputs("File Handling\n", file);
    fputs("Practice Makes Perfect\n", file);
    fputs("Keep Learning C\n", file);

    fclose(file);

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

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

    while ((ch = fgetc(file)) != EOF)
    {
        if (ch == '\n')
        {
            lines++;
        }
    }

    fclose(file);

    printf("Total lines = %d", lines);

    return 0;
}

Sample Output

Total lines = 4

Explanation

Every line ends with:

'\n'

So the program checks:

if (ch == '\n')

Whenever a newline character is found, the line count increases.

For this file:

C Programming
File Handling
Practice Makes Perfect
Keep Learning C

there are four newline characters.

Concepts Covered

  • fgetc()
  • EOF
  • Newline character
  • if
  • File reading

Q3. Count the Number of Words in a File

Problem Statement

Write a C program to count the number of words stored in a text file.

C Program

#include <stdio.h>
#include <ctype.h>

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

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

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

    fputs("C is easy to learn", file);

    fclose(file);

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

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

    while ((ch = fgetc(file)) != EOF)
    {
        if (isspace(ch))
        {
            inside_word = 0;
        }
        else if (inside_word == 0)
        {
            words++;
            inside_word = 1;
        }
    }

    fclose(file);

    printf("Total words = %d", words);

    return 0;
}

Sample Output

Total words = 5

Explanation

The file contains:

C is easy to learn

There are five words.

The variable:

inside_word

keeps track of whether the program is currently inside a word.

When whitespace is found:

if (isspace(ch))

the program knows that the current word has ended.

When a non-whitespace character appears after whitespace, a new word begins.

The program uses:

#include <ctype.h>

for the isspace() function.

Concepts Covered

  • fgetc()
  • isspace()
  • Word counting
  • Boolean-style flag
  • File reading

Q4. Copy the Contents of One File to Another

Problem Statement

Create a source file and copy all its contents into another file.

C Program

#include <stdio.h>

int main()
{
    FILE *source;
    FILE *destination;
    int ch;

    source = fopen("source.txt", "w");

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

    fputs("This is the original file.\n", source);
    fputs("This content will be copied.", source);

    fclose(source);

    source = fopen("source.txt", "r");

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

    destination = fopen("copy.txt", "w");

    if (destination == NULL)
    {
        printf("Destination file could not be opened");
        fclose(source);
        return 1;
    }

    while ((ch = fgetc(source)) != EOF)
    {
        fputc(ch, destination);
    }

    fclose(source);
    fclose(destination);

    printf("File copied successfully");

    return 0;
}

Sample Output

File copied successfully

Content of copy.txt

This is the original file.
This content will be copied.

Explanation

The source file is opened in read mode:

source = fopen("source.txt", "r");

The destination file is opened in write mode:

destination = fopen("copy.txt", "w");

Then:

while ((ch = fgetc(source)) != EOF)
{
    fputc(ch, destination);
}

reads one character from the source and writes the same character to the destination.

Concepts Covered

  • Multiple file pointers
  • fgetc()
  • fputc()
  • File copying
  • EOF

Q5. Search for a Character in a File

Problem Statement

Write a C program that searches for a particular character in a file and counts how many times it appears.

C Program

#include <stdio.h>

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

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

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

    fputs("banana", file);

    fclose(file);

    printf("Enter character to search: ");
    scanf(" %c", &search);

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

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

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

    fclose(file);

    printf("Character '%c' appears %d times", search, count);

    return 0;
}

Sample Output

Enter character to search: a
Character 'a' appears 3 times

Explanation

The program stores:

banana

in the file.

The user enters:

a

The program reads every character and compares it with:

if (ch == search)

Whenever they match, count increases.

The space before %c:

scanf(" %c", &search);

helps skip leftover whitespace before reading the character.

Concepts Covered

  • Character searching
  • fgetc()
  • scanf()
  • if
  • Counter

Q6. Store and Read Student Records from a File

Problem Statement

Write a C program that stores three student records in a file and then reads them from the file.

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");

    while (fscanf(file, "%49s %d %f", name, &age, &marks) == 3)
    {
        printf("Name: %s\n", name);
        printf("Age: %d\n", age);
        printf("Marks: %.2f\n\n", marks);
    }

    fclose(file);

    return 0;
}

Sample Output

Student Records

Name: Rahul
Age: 18
Marks: 85.50

Name: Aman
Age: 17
Marks: 91.00

Name: Priya
Age: 19
Marks: 88.50

Explanation

Each record contains:

Name Age Marks

For example:

Rahul 18 85.5

The program uses:

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

to read one record at a time.

The loop continues while three values are successfully read:

== 3

This is a useful pattern when reading structured text files.

Concepts Covered

  • fprintf()
  • fscanf()
  • Student records
  • while
  • File-based data storage

Q7. Calculate the Sum of Numbers Stored in a File

Problem Statement

Create a file containing integers and calculate their total sum by reading them from the file.

C Program

#include <stdio.h>

int main()
{
    FILE *file;
    int number;
    int sum = 0;

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

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

    fprintf(file, "10 20 30 40 50");

    fclose(file);

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

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

    while (fscanf(file, "%d", &number) == 1)
    {
        sum += number;
    }

    fclose(file);

    printf("Sum = %d", sum);

    return 0;
}

Sample Output

Sum = 150

Explanation

The file contains:

10 20 30 40 50

The program reads one integer at a time:

while (fscanf(file, "%d", &number) == 1)

Each number is added:

sum += number;

The calculation is:

10 + 20 + 30 + 40 + 50 = 150

Concepts Covered

  • fscanf()
  • Integer input from files
  • while
  • Addition
  • File reading

Q8. Append a New Student to an Existing File

Problem Statement

Create a file containing student records and then append a new student’s information without deleting the existing records.

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;
    }

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

    fclose(file);

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

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

    fprintf(file, "Priya 19 88.5\n");

    fclose(file);

    printf("New student added successfully");

    return 0;
}

Sample Output

New student added successfully

Final File Content

Rahul 18 85.5
Aman 17 91.0
Priya 19 88.5

Explanation

First, the file is created using:

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

Two students are written.

Then the file is reopened using:

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

The "a" mode means append.

Therefore:

fprintf(file, "Priya 19 88.5\n");

adds the new record at the end without removing the existing records.

Concepts Covered

  • Append mode
  • fprintf()
  • Student records
  • Existing file data
  • File updating

Q9. Find the Largest Number Stored in a File

Problem Statement

Create a file containing integers and find the largest number stored in it.

C Program

#include <stdio.h>

int main()
{
    FILE *file;
    int number;
    int largest;
    int first = 1;

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

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

    fprintf(file, "25 70 15 90 45 60");

    fclose(file);

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

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

    while (fscanf(file, "%d", &number) == 1)
    {
        if (first == 1)
        {
            largest = number;
            first = 0;
        }
        else if (number > largest)
        {
            largest = number;
        }
    }

    fclose(file);

    if (first == 1)
    {
        printf("No numbers found in file");
    }
    else
    {
        printf("Largest number = %d", largest);
    }

    return 0;
}

Sample Output

Largest number = 90

Explanation

The file contains:

25 70 15 90 45 60

The first number is initially considered the largest.

Then every next number is compared:

else if (number > largest)
{
    largest = number;
}

When 90 is found, it becomes the new largest value.

The first variable also handles the case where the file contains no numbers.

Concepts Covered

  • fscanf()
  • File-based number processing
  • if-else
  • Largest value
  • Flag variable

Q10. Create a Simple File-Based Marks Report

Problem Statement

Store student names and marks in a file. Read the records and calculate the average marks.

C Program

#include <stdio.h>

int main()
{
    FILE *file;
    char name[50];
    float marks;
    float total = 0.0f;
    int count = 0;

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

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

    fprintf(file, "Rahul 85.5\n");
    fprintf(file, "Aman 91.0\n");
    fprintf(file, "Priya 88.5\n");
    fprintf(file, "Neha 79.0\n");

    fclose(file);

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

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

    printf("Marks Report\n\n");

    while (fscanf(file, "%49s %f", name, &marks) == 2)
    {
        printf("%s: %.2f\n", name, marks);

        total += marks;
        count++;
    }

    fclose(file);

    if (count > 0)
    {
        printf("\nAverage Marks = %.2f", total / count);
    }
    else
    {
        printf("\nNo student records found");
    }

    return 0;
}

Sample Output

Marks Report

Rahul: 85.50
Aman: 91.00
Priya: 88.50
Neha: 79.00

Average Marks = 86.00

Explanation

The file stores:

Rahul 85.5
Aman 91.0
Priya 88.5
Neha 79.0

Each record contains:

Name Marks

The program reads the name and marks using:

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

Then it adds the marks:

total += marks;

and counts the students:

count++;

Finally:

total / count

calculates the average.

Concepts Covered

  • fprintf()
  • fscanf()
  • File records
  • Loops
  • Average calculation
  • Conditional statements
  • File handling

Key Takeaways

  • File handling practice helps turn individual file functions into complete programs.
  • fopen() is used to open files.
  • fclose() in C should be used when file operations are finished.
  • fgetc() is useful for character-by-character processing.
  • fgets() is useful for reading lines.
  • fscanf() is useful for reading structured data.
  • fprintf() is useful for writing formatted data.
  • fputc() writes one character.
  • fputs() writes a string.
  • "a" mode allows new data to be appended without replacing existing contents.
  • EOF can be used to detect the end of a file when reading characters.
  • File handling can be combined with loops, conditions, counters, arrays, and calculations to create practical programs.
  • Always validate file opening and avoid reading or writing through a NULL file pointer.

FAQs

1. What can I practice after learning basic file handling in C?

You can practice counting characters, words and lines, copying files, searching text, storing records, calculating totals and averages, and appending new records.

2. Which function is used to read a character from a file?

fgetc() reads one character from a file.

int ch = fgetc(file);

3. How can I copy one file to another in C?

Open the source file in read mode and the destination file in write mode. Then read characters using fgetc() and write them using fputc() until EOF is reached.

4. How do I count words in a C file?

You can read the file character by character and detect transitions between whitespace and non-whitespace characters. The isspace() function from <ctype.h> can help identify spaces, tabs, and newlines.

5. How can I add new data without deleting existing file content?

Open the file using append mode:

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

New output is then written at the end of the file.

6. How can I read multiple records from a file?

If the records follow a predictable format, you can repeatedly call fscanf() inside a loop.

while (fscanf(file, "%49s %d", name, &age) == 2)
{
    printf("%s %d\n", name, age);
}

7. Why should I practice file handling with real programs?

Practical programs help you understand how fopen(), reading, writing, loops, conditions, and fclose() work together. They also prepare you for larger programs that need to save information permanently.

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

Scroll to Top