0
0
C++programming~5 mins

Why file handling is required in C++

Choose your learning style9 modes available
Introduction

File handling lets programs save and read data from files. This helps keep information even after the program stops running.

Saving user settings so they stay the same next time the program runs.
Storing game scores or progress to continue later.
Reading a list of names or data from a file to use in the program.
Logging errors or events while the program runs for later review.
Sharing data between different programs or sessions.
Syntax
C++
// In C++, file handling uses fstream library
#include <fstream>

// To open a file for writing
std::ofstream file("filename.txt");

// To open a file for reading
std::ifstream file("filename.txt");

// To write data
file << "Hello";

// To read data
file >> variable;

// Close the file
file.close();

Use #include <fstream> to work with files.

ofstream is for writing, ifstream is for reading files.

Examples
This example writes the text "Hello, file!" to a file named data.txt.
C++
#include <fstream>

int main() {
    std::ofstream outFile("data.txt");
    outFile << "Hello, file!";
    outFile.close();
    return 0;
}
This example reads the first word from data.txt and prints it.
C++
#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream inFile("data.txt");
    std::string content;
    inFile >> content;
    std::cout << content << std::endl;
    inFile.close();
    return 0;
}
Sample Program

This program writes a sentence to a file and then reads it back to show how file handling works.

C++
#include <fstream>
#include <iostream>
#include <string>

int main() {
    // Create and open a file
    std::ofstream file("example.txt");
    
    // Write some text to the file
    file << "File handling in C++ is useful.";
    
    // Close the file
    file.close();

    // Open the file to read
    std::ifstream readFile("example.txt");
    std::string text;
    
    // Read the content
    std::getline(readFile, text);

    // Print the content
    std::cout << text << std::endl;

    // Close the file
    readFile.close();

    return 0;
}
OutputSuccess
Important Notes

Always close files after opening to save changes and free resources.

File handling helps keep data safe even when the program stops.

Summary

File handling lets programs save and load data from files.

It is useful for saving user data, settings, and logs.

C++ uses fstream library to work with files.