Files are essential for storing data persistently beyond the lifetime of a program. They allow you to create, read, write, and manipulate information on your computer's storage devices. C++ offers powerful mechanisms for file handling using file streams.
ios::out
(ofstream): Creates a new file or overwrites an existing one for writing.ios::in
(ifstream): Opens an existing file for reading.ios::app
(ofstream): Appends data to the end of an existing file.ios::binary
(fstream): Enables binary mode for reading or writing raw bytes. The default is text mode, which interprets line endings differently across operating systems.C++ provides three primary classes for file handling, all declared in the <fstream>
header:
C++ provides three primary classes for file handling, all declared in the <fstream>
header:
Similarly, we use the ofstream
class to perform output operations on a file.
#include
#include
using namespace std;
int main() {
ofstream outputFile;
outputFile.open("output.txt");
if (!outputFile) {
cout << "Unable to open file";
return 1;
}
// File is opened successfully, perform operations...
outputFile.close();
return 0;
}
Once the output file is open, we can write data to it using the insertion operator <<
.
#include
#include
using namespace std;
int main() {
ofstream outputFile;
outputFile.open("output.txt");
if (!outputFile) {
cout << "Unable to open file";
return 1;
}
outputFile << "Hello, World!\n";
outputFile << "This is a new line.";
outputFile.close();
return 0;
}
// output //
Output: (Contents of "output.txt")
File handling in C++ is a powerful feature that enables programmers to interact with external files efficiently. By understanding the basic concepts and utilizing the input and output stream classes (ifstream and ofstream), developers can manipulate files seamlessly. Whether it's reading from a data file or saving user-generated content, file handling provides a robust mechanism for data persistence in C++ programs.Happy coding !❤️