Lesson 56 of 60 – File Handling in C++
93%

File Handling in C++

File handling in C++ allows a program to create, open, read, write, append, and manage data stored in files. C++ provides file stream classes such as std::ifstream, std::ofstream, and std::fstream for working with files.

Note: File handling is useful when data needs to be stored permanently instead of keeping it only in program memory.

1. What is File Handling?

File handling means working with files to store and retrieve data.

A C++ program can perform operations such as:

  • Create a file
  • Open a file
  • Write data to a file
  • Read data from a file
  • Append data to a file
  • Close a file

File handling allows information to remain available even after the program ends.

2. Why Use Files?

Variables store data temporarily while a program is running. Files allow data to be stored for later use.

For example, a student management program can store:

  • Student names
  • Student IDs
  • Marks
  • Addresses
  • Fee records

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

3. File Stream Classes

C++ provides file stream classes in the <fstream> header.

Class Purpose
std::ifstream Used for reading from files.
std::ofstream Used for writing to files.
std::fstream Used for both reading and writing.

4. Include the fstream Header

To work with files, include the <fstream> header.

#include <fstream>

For example:

#include <iostream>
#include <fstream>

int main() {

    std::ofstream file;

    return 0;
}

5. Creating an Output File Stream

An std::ofstream object is commonly used to write data to a file.

#include <fstream>

int main() {

    std::ofstream file;

    file.open("data.txt");

    file.close();

    return 0;
}

If the operation succeeds, the file can be created or opened for output according to the selected mode.

6. Writing to a File

The insertion operator << can be used to write data to an output file stream.

#include <fstream>

int main() {

    std::ofstream file(
        "data.txt"
    );

    file <<
        "Hello C++";

    file.close();

    return 0;
}

The text is written to data.txt.

7. Writing Multiple Lines

#include <fstream>

int main() {

    std::ofstream file(
        "student.txt"
    );

    file <<
        "Name: Rahul\n";

    file <<
        "Age: 20\n";

    file <<
        "Course: C++\n";

    file.close();

    return 0;
}

The newline character \n can be used to write multiple lines.

8. Checking Whether a File Opened Successfully

It is good practice to check whether the file was opened successfully.

#include <fstream>
#include <iostream>

int main() {

    std::ofstream file(
        "data.txt"
    );

    if(!file) {

        std::cout <<
            "File could not be opened";

        return 1;
    }

    file <<
        "Hello C++";

    file.close();

    return 0;
}

9. Reading from a File

The std::ifstream class is used to read data from a file.

#include <fstream>
#include <iostream>

int main() {

    std::ifstream file(
        "data.txt"
    );

    std::string text;

    file >> text;

    std::cout <<
        text;

    file.close();

    return 0;
}

The extraction operator >> reads formatted data.

10. Reading a Complete Line

Use std::getline() when you want to read an entire line, including spaces.

#include <fstream>
#include <iostream>
#include <string>

int main() {

    std::ifstream file(
        "data.txt"
    );

    std::string line;

    while(
        std::getline(file, line)
    ) {

        std::cout <<
            line
            << std::endl;
    }

    file.close();

    return 0;
}

11. Reading a File Line by Line

A common pattern for reading a text file is:

std::string line;

while(
    std::getline(file, line)
) {

    std::cout <<
        line
        << std::endl;
}

The loop continues while std::getline() successfully reads a line.

12. Opening a File Using open()

A file stream can be created first and opened later using open().

std::ofstream file;

file.open("data.txt");

file <<
    "Hello";

file.close();

This approach is useful when the file name or opening operation needs to be controlled separately.

13. Closing a File

The close() function closes an open file stream.

std::ofstream file(
    "data.txt"
);

file <<
    "Some data";

file.close();

Closing a file releases the stream's associated resources and finishes the output operation.

14. File Open Modes

C++ provides different file opening modes.

Mode Purpose
std::ios::in Open for input.
std::ios::out Open for output.
std::ios::app Append output at the end of the file.
std::ios::ate Open and initially position at the end.
std::ios::trunc Truncate existing output when the mode applies.
std::ios::binary Open in binary mode.

15. Append Data to a File

The std::ios::app mode is used to append output to the end of a file.

#include <fstream>

int main() {

    std::ofstream file(
        "data.txt",
        std::ios::app
    );

    file <<
        "New line added\n";

    file.close();

    return 0;
}

Existing file content is preserved while new output is written at the end.

16. Reading and Writing with fstream

The std::fstream class can be used for both input and output.

#include <fstream>

int main() {

    std::fstream file(
        "data.txt",
        std::ios::in |
        std::ios::out
    );

    return 0;
}

The exact behavior also depends on the file's existing state and the opening modes used.

17. File Position Pointers

File streams maintain positions used for reading and writing. Common functions include:

  • tellg() – gets the current input position.
  • seekg() – changes the input position.
  • tellp() – gets the current output position.
  • seekp() – changes the output position.
std::ifstream file(
    "data.txt"
);

std::cout <<
    file.tellg();

18. tellg() Function

The tellg() function returns the current input position of a stream.

std::ifstream file(
    "data.txt"
);

std::cout <<
    "Position: "
    << file.tellg();

It is useful when working with file positions during input operations.

19. seekg() Function

The seekg() function changes the input position.

std::ifstream file(
    "data.txt"
);

file.seekg(0);

std::string line;

std::getline(
    file,
    line
);

The position can be moved to a desired location before reading.

20. tellp() and seekp()

For output positioning, C++ provides tellp() and seekp().

std::ofstream file(
    "data.txt"
);

file <<
    "Hello";

std::cout <<
    file.tellp();

file.seekp(0);

These functions are useful when controlling the output position.

21. Checking End of File

A common and reliable pattern for reading text files is to test the actual read operation.

std::string line;

while(
    std::getline(file, line)
) {

    std::cout <<
        line
        << std::endl;
}

Avoid using eof() as the primary loop condition because end-of-file is normally detected after a read attempt fails.

22. Checking File State

C++ stream objects provide functions to inspect stream state.

  • is_open() – checks whether the stream is associated with an open file.
  • good() – indicates that no error state is currently set.
  • fail() – checks for a logical or input/output failure.
  • bad() – checks for a serious stream error.
  • eof() – checks whether the end-of-file state is set.
if(file.is_open()) {

    std::cout <<
        "File is open";
}

23. Writing Student Records

#include <fstream>
#include <iostream>

int main() {

    std::ofstream file(
        "students.txt"
    );

    if(!file) {

        std::cout <<
            "Unable to open file";

        return 1;
    }

    file <<
        "101 Rahul 85\n";

    file <<
        "102 Priya 92\n";

    file <<
        "103 Amit 78\n";

    file.close();

    return 0;
}

This program stores simple student records in a text file.

24. Reading Student Records

#include <fstream>
#include <iostream>

int main() {

    std::ifstream file(
        "students.txt"
    );

    if(!file) {

        std::cout <<
            "Unable to open file";

        return 1;
    }

    int id;
    std::string name;
    int marks;

    while(
        file >>
        id >>
        name >>
        marks
    ) {

        std::cout <<
            id << " "
            << name << " "
            << marks
            << std::endl;
    }

    file.close();

    return 0;
}

Formatted extraction is useful when the file contains predictable whitespace-separated data.

25. Binary File Handling

Binary mode allows a stream to process file data as binary rather than text-oriented data.

#include <fstream>

int main() {

    int number = 100;

    std::ofstream file(
        "data.bin",
        std::ios::binary
    );

    file.write(
        reinterpret_cast<const char*>(
            &number
        ),
        sizeof(number)
    );

    file.close();

    return 0;
}

Binary files are commonly used when working with raw object representations or specific binary formats. Such representations are not automatically portable or suitable for every type.

26. Common File Handling Mistakes

  • Forgetting to include <fstream>.
  • Failing to check whether a file opened successfully.
  • Using the wrong file opening mode.
  • Accidentally replacing file content when append mode was intended.
  • Using eof() incorrectly as the primary read-loop condition.
  • Reading data with the wrong type or format.
  • Forgetting to handle file errors.
  • Using unsafe assumptions when reading binary data.

27. Advantages of File Handling

  • Permanent Storage: Data can remain after the program exits.
  • Data Sharing: Files can be used to exchange information between programs.
  • Large Data: Files can store more information than temporary variables.
  • Record Management: Applications can store user, student, employee, and transaction records.
  • Data Recovery: Previously stored information can be loaded again.

28. Best Practices for File Handling

  • Always check whether a file opened successfully.
  • Use the appropriate stream class for the operation.
  • Use std::getline() when complete text lines are required.
  • Use append mode when existing content must be preserved.
  • Check stream state when file operations can fail.
  • Use RAII-based stream objects instead of unnecessary manual resource management.
  • Choose text or binary format according to the application's requirements.
  • Validate data read from external files.

29. Practical File Management Example

#include <iostream>
#include <fstream>
#include <string>

int main() {

    {
        std::ofstream file(
            "students.txt"
        );

        if(!file) {

            std::cout <<
                "File could not be opened";

            return 1;
        }

        file <<
            "Rahul\n";

        file <<
            "Priya\n";

        file <<
            "Amit\n";
    }

    {
        std::ifstream file(
            "students.txt"
        );

        if(!file) {

            std::cout <<
                "File could not be opened";

            return 1;
        }

        std::string name;

        while(
            std::getline(
                file,
                name
            )
        ) {

            std::cout <<
                name
                << std::endl;
        }
    }

    return 0;
}

The output stream writes student names and the input stream later reads them line by line.

30. File Handling – Final Summary

Concept Meaning
std::ifstream Used for input from files.
std::ofstream Used for output to files.
std::fstream Used for both input and output.
open() Opens a file stream.
close() Closes the file stream.
std::getline() Reads a complete line from a text stream.
std::ios::app Appends output at the end of a file.
tellg() / seekg() Get or change the input position.
tellp() / seekp() Get or change the output position.
std::ios::binary Opens a stream in binary mode.
#include <fstream>
#include <iostream>
#include <string>

int main() {

    std::ofstream out(
        "data.txt"
    );

    if(!out) {

        std::cout <<
            "Unable to open file";

        return 1;
    }

    out <<
        "C++ File Handling";

    out.close();

    std::ifstream in(
        "data.txt"
    );

    if(!in) {

        std::cout <<
            "Unable to open file";

        return 1;
    }

    std::string line;

    while(
        std::getline(in, line)
    ) {

        std::cout <<
            line;
    }

    return 0;
}

File handling allows C++ programs to store and retrieve information from external files. Understanding streams, file modes, reading, writing, and stream states is essential for building applications that work with persistent data.

📌 Key Points

  • C++ file handling is provided mainly through the <fstream> library.
  • std::ifstream is commonly used for reading files.
  • std::ofstream is commonly used for writing files.
  • std::fstream can be used for both reading and writing.
  • std::getline() reads complete lines.
  • std::ios::app is useful for appending data.
  • tellg() and seekg() work with input positions.
  • tellp() and seekp() work with output positions.
  • Always check whether file operations succeed.
  • Use RAII and stream objects to manage file resources safely.

🧠 Quick Quiz

Question: Which C++ class is commonly used to read data from a file?