File handling
in C++ is a crucial aspect of programming that allows you to read data from and write data to files. C++ provides a set of standard library classes and functions for file handling, which are part of the
header. There are three main classes involved in file handling in C++:
1. ofstream (Output File Stream):
Used to create and write to files.
2. ifstream (Input File Stream):
Used to read from files.
3. fstream (File Stream):
Can be used for both reading and writing.
Writing to a File (ofstream):
To write data to a file, you can use the ofstream class. Here's a simple example:
#include <iostream>
Copy Code
#include <fstream>
int
main
() {
std::ofstream
outFile
("example.txt");
if
(
outFile
.
is_open
()) {
outFile
<<
"Hello, File Handling in C++!"
<<
;
outFile
<<
42
;
outFile
.
close
();
}
else
{
std::cerr
<<
"Unable to open the file for writing."
<<
;
}
return
0
;
}
Reading from a File (ifstream):
To read data from a file, you can use the ifstream class. Here's an example:
#include <iostream>
Copy Code
#include <fstream>
#include <string>
int
main
() {
std::ifstream
inFile
("example.txt");
if
(
inFile
.
is_open
()) {
std::string
line
;
while
(
std::getline
(
inFile
,
line
)) {
std::cout
<<
line
<<
std::endl
;
}
inFile
.
close
();
}
else
{
std::cerr
<<
"Unable to open the file for reading."
<<
std::endl
;
}
return
0;
}
Reading and Writing using fstream:
You can use the fstream class to perform both read and write operations on a file.
#include <iostream>
Copy Code
#include <fstream>
#include <string>
int
main
() {
std::fstream
file(
"example.txt"
,
std::ios::in
|
std::ios::out
|
std::ios::app
);
if
(file.
is_open
()) {
file <<
"Appending more data.
"
;
file.
seekg
(0);
std::string
line;
while
(
std::getline
(file, line)) {
std::cout
<< line <<
std::endl
;
}
file.
close
();
}
else
{
std::cerr
<<
"Unable to open the file.
"
;
}
return
0;
}
These are just basic examples, and there are many other features and functions available for file handling in C++. Make sure to handle exceptions and errors appropriately, especially when dealing with file I/O operations.