Working with Files
Include the
<fstream>
Library
To use file handling features, include the<fstream>
library:
Opening and Closing a File
Files are opened using the open()
method or during object creation. Always close files after use with close()
.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Write to a file
ofstream outfile("example.txt");
if (outfile.is_open()) {
outfile << "Hello, File Handling in C++!\n";
outfile.close();
} else {
cout << "Unable to open file for writing.\n";
}
// Read from a file
ifstream infile("example.txt");
string line;
if (infile.is_open()) {
while (getline(infile, line)) {
cout << line << endl; // Print the content to the console
}
infile.close();
} else {
cout << "Unable to open file for reading.\n";
}
return 0;
}
Loved the way you present all the topics , it makes everything , especially learning very interesting and fascinating sir , hats off to you!
ReplyDelete