Introduction
File handling lets programs save and read data from files. This helps keep information even after the program stops running.
File handling lets programs save and read data from files. This helps keep information even after the program stops running.
// 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.
#include <fstream> int main() { std::ofstream outFile("data.txt"); outFile << "Hello, file!"; outFile.close(); return 0; }
#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; }
This program writes a sentence to a file and then reads it back to show how file handling works.
#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; }
Always close files after opening to save changes and free resources.
File handling helps keep data safe even when the program stops.
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.
fstream library is used in C++ for file input and output operations.#include <fstream> provides file handling capabilities, others are for different purposes.#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file("data.txt");
file << "Hello World";
file.close();
ifstream readFile("data.txt");
string content;
readFile >> content;
cout << content;
return 0;
}#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file;
file.open("info.txt");
string data;
file >> data;
cout << data;
return 0;
}cout but does not include <iostream>, which is required for input/output streams.ofstream writes data to files, and ifstream reads data from files, making them suitable for this task.Pass the test and this pattern moves unknown