C++ File Handling Practice Questions with Solutions

File handling is one of the most practical concepts in C++. It allows programs to store data permanently in files instead of keeping it only in memory. With file handling, you can create, read, write, append, and update files, making applications more useful in real-world scenarios. C++ File Handling practice questions with solutions help to build concepts.

C++ provides the <fstream> library for working with files.

The three main file stream classes are:

  • ofstream – Used to create and write data to a file.
  • ifstream – Used to read data from a file.
  • fstream – Used for both reading and writing.

Why File Handling is Important

File handling is widely used in:

  • Student Management Systems
  • Employee Databases
  • Banking Applications
  • Inventory Management
  • Billing Software
  • Hospital Management Systems
  • Game Save Files
  • Configuration Files

Common File Operations

  • Create a file
  • Write data to a file
  • Read data from a file
  • Append new data
  • Check if a file exists
  • Copy data between files

Example of writing to a file:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream file("student.txt");

    file << "Welcome to C++ File Handling";

    file.close();

    return 0;
}

Example of reading a file:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file("student.txt");

    string line;

    getline(file, line);

    cout << line;

    file.close();

    return 0;
}

In this chapter, you’ll solve beginner-friendly C++ File Handling practice questions with complete explanations.

Each question includes:

  • Problem Statement
  • Complete C++ Solution
  • Sample Output
  • Explanation
  • Concepts Covered

Let’s begin.


1. C++ Program to Create and Write to a File

Problem Statement

Write a C++ program to create a text file and write a message into it.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream file("sample.txt");

    file << "Welcome to C++ File Handling.";

    file.close();

    cout << "Data written successfully.";

    return 0;
}

Sample Output

Data written successfully.

Explanation

The ofstream class creates the file (if it does not exist) and writes the specified text into it.

Concepts Covered

  • ofstream
  • File Creation
  • File Writing

2. C++ Program to Read Data from a File

Problem Statement

Write a C++ program to read and display the contents of a text file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file("sample.txt");

    string line;

    getline(file, line);

    cout << line;

    file.close();

    return 0;
}

Sample Output

Welcome to C++ File Handling.

Explanation

The ifstream class opens the file in read mode and retrieves its contents.

Concepts Covered

  • ifstream
  • File Reading
  • getline()

3. C++ Program to Append Data to a File

Problem Statement

Write a C++ program to append new text to an existing file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream file("sample.txt", ios::app);

    file << "\nLearning File Handling.";

    file.close();

    cout << "Data appended successfully.";

    return 0;
}

Sample Output

Data appended successfully.

Explanation

The ios::app mode appends new data to the end of the existing file without deleting previous content.

Concepts Covered

  • Append Mode
  • ios::app
  • File Writing

4. C++ Program to Read File Line by Line

Problem Statement

Write a C++ program to read a file line by line.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file("sample.txt");

    string line;

    while (getline(file, line))
    {
        cout << line << endl;
    }

    file.close();

    return 0;
}

Sample Output

Welcome to C++ File Handling.
Learning File Handling.

Explanation

The while loop continues reading each line until the end of the file.

Concepts Covered

  • getline()
  • Loops
  • File Reading

5. C++ Program to Count the Number of Lines in a File

Problem Statement

Write a C++ program to count the total number of lines in a text file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file("sample.txt");

    string line;

    int count = 0;

    while (getline(file, line))
    {
        count++;
    }

    cout << "Total Lines = "
         << count;

    file.close();

    return 0;
}

Sample Output

Total Lines = 2

Explanation

Each successful call to getline() increases the line counter until the end of the file is reached.

Concepts Covered

  • File Reading
  • Loop
  • Line Counting

6. C++ Program to Count the Number of Words in a File

Problem Statement

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

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file("sample.txt");

    string word;

    int count = 0;

    while (file >> word)
    {
        count++;
    }

    cout << "Total Words = "
         << count;

    file.close();

    return 0;
}

Sample Output

Total Words = 6

Explanation

The extraction operator (>>) reads one word at a time until the end of the file.

Concepts Covered

  • Word Counting
  • File Reading
  • Loop

7. C++ Program to Count the Number of Characters in a File

Problem Statement

Write a C++ program to count the total number of characters in a file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file("sample.txt");

    char character;

    int count = 0;

    while (file.get(character))
    {
        count++;
    }

    cout << "Total Characters = "
         << count;

    file.close();

    return 0;
}

Sample Output

Total Characters = 52

Explanation

The get() function reads one character at a time, including spaces and special characters.

Concepts Covered

  • Character Counting
  • get()
  • File Reading

8. C++ Program to Copy Data from One File to Another

Problem Statement

Write a C++ program to copy the contents of one file into another file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream source("sample.txt");

    ofstream destination("copy.txt");

    string line;

    while (getline(source, line))
    {
        destination << line << endl;
    }

    source.close();
    destination.close();

    cout << "File copied successfully.";

    return 0;
}

Sample Output

File copied successfully.

Explanation

The program reads each line from the source file and writes it into the destination file.

Concepts Covered

  • File Copy
  • ifstream
  • ofstream

9. C++ Program to Check Whether a File Exists

Problem Statement

Write a C++ program to check whether a file exists.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file("sample.txt");

    if (file)
    {
        cout << "File Exists";
    }
    else
    {
        cout << "File Not Found";
    }

    file.close();

    return 0;
}

Sample Output

File Exists

Explanation

If the file opens successfully, it exists. Otherwise, the file does not exist or cannot be accessed.

Concepts Covered

  • File Existence Check
  • ifstream
  • Conditional Statements

10. C++ Program to Store Student Records in a File

Problem Statement

Write a C++ program to store student details in a text file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream file("students.txt");

    file << "101 Rahul 92\n";
    file << "102 Priya 95\n";
    file << "103 Amit 88";

    file.close();

    cout << "Student records saved successfully.";

    return 0;
}

Sample Output

Student records saved successfully.

Explanation

The program creates a file and stores multiple student records in a structured format.

Concepts Covered

  • File Writing
  • Student Records
  • Data Storage

11. C++ Program to Read Student Records from a File

Problem Statement

Write a C++ program to read and display student records stored in a file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file("students.txt");

    int rollNumber;
    string name;
    int marks;

    while (file >> rollNumber >> name >> marks)
    {
        cout << "Roll Number: " << rollNumber << endl;
        cout << "Name: " << name << endl;
        cout << "Marks: " << marks << endl;
        cout << endl;
    }

    file.close();

    return 0;
}

Sample Output

Roll Number: 101
Name: Rahul
Marks: 92

Roll Number: 102
Name: Priya
Marks: 95

Roll Number: 103
Name: Amit
Marks: 88

Explanation

The program reads one complete student record at a time and displays it until the end of the file.

Concepts Covered

  • File Reading
  • Structured Data
  • Loops

12. C++ Program to Copy Only Even Numbers from One File to Another

Problem Statement

Write a C++ program to copy only even numbers from one file into another file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream inputFile("numbers.txt");

    ofstream outputFile("even.txt");

    int number;

    while (inputFile >> number)
    {
        if (number % 2 == 0)
        {
            outputFile << number << " ";
        }
    }

    inputFile.close();
    outputFile.close();

    cout << "Even numbers copied successfully.";

    return 0;
}

Sample Output

Even numbers copied successfully.

Explanation

The program reads numbers from one file and writes only even numbers into another file.

Concepts Covered

  • File Copy
  • Conditional Statements
  • File Writing

13. C++ Program to Merge Two Files

Problem Statement

Write a C++ program to merge the contents of two text files into a third file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file1("file1.txt");
    ifstream file2("file2.txt");

    ofstream mergedFile("merged.txt");

    string line;

    while (getline(file1, line))
    {
        mergedFile << line << endl;
    }

    while (getline(file2, line))
    {
        mergedFile << line << endl;
    }

    file1.close();
    file2.close();
    mergedFile.close();

    cout << "Files merged successfully.";

    return 0;
}

Sample Output

Files merged successfully.

Explanation

The program copies all data from the first file followed by all data from the second file into a new file.

Concepts Covered

  • Multiple Files
  • File Reading
  • File Writing

14. C++ Program to Display File Size

Problem Statement

Write a C++ program to determine the size of a file.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream file("sample.txt", ios::binary | ios::ate);

    cout << "File Size = "
         << file.tellg()
         << " bytes";

    file.close();

    return 0;
}

Sample Output

File Size = 58 bytes

Explanation

The file pointer is moved to the end of the file using ios::ate, and tellg() returns the file size in bytes.

Concepts Covered

  • File Size
  • tellg()
  • File Pointer

15. C++ Program to Demonstrate Complete File Handling

Problem Statement

Write a C++ program that demonstrates file creation, writing, reading, and closing operations.

C++ Solution

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream outputFile("demo.txt");

    outputFile << "Welcome to C++ File Handling.";

    outputFile.close();

    ifstream inputFile("demo.txt");

    string line;

    getline(inputFile, line);

    cout << line;

    inputFile.close();

    return 0;
}

Sample Output

Welcome to C++ File Handling.

Explanation

This example combines file creation, writing, reading, and closing into a single program, demonstrating the complete file handling workflow.

Concepts Covered

  • File Creation
  • File Reading
  • File Writing
  • File Closing

Chapter Summary

In this chapter, you learned the fundamentals of File Handling in C++. You explored how to create files, write data, read data, append information, count lines, words, and characters, check file existence, copy and merge files, calculate file size, and work with structured records. These concepts are essential for developing real-world applications that require permanent data storage, reporting, and data management.


Key Takeaways

  • The <fstream> library provides file handling support in C++.
  • ofstream is used to create and write files.
  • ifstream is used to read files.
  • fstream supports both reading and writing.
  • Always close files after use to release system resources.
  • getline() reads complete lines from a file.
  • ios::app appends data without overwriting existing content.
  • tellg() returns the current file position and can be used to determine file size.
  • File handling is widely used in database-like applications, reporting systems, and record management.
  • Proper error checking improves file handling reliability.

Frequently Asked Questions (FAQs)

1. Which header file is required for file handling in C++?

The <fstream> header file is required for file handling.


2. What is the difference between ifstream and ofstream?

  • ifstream is used for reading files.
  • ofstream is used for writing files.

3. What is fstream?

fstream is a file stream class that supports both reading and writing operations.


4. What does ios::app do?

ios::app opens a file in append mode so that new data is added to the end of the file instead of replacing existing content.


5. Why should files be closed after use?

Closing files releases system resources, ensures all buffered data is written, and prevents file corruption.


6. How can you check whether a file exists?

You can attempt to open the file using ifstream. If the stream opens successfully, the file exists.


7. What is the purpose of tellg()?

tellg() returns the current position of the file pointer and is commonly used to determine the size of a file.


8. Why is file handling important in C++?

File handling allows programs to store and retrieve data permanently, making it essential for applications such as student management systems, banking software, inventory systems, and report generation.

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

Scroll to Top