There are a couple of ways one could open a file:
- Open for read
- Open for write
- Open for read and write
In order to open a file, you must include the fstream header, like this:
#include <fstream>
This allows you to use the fstream object, like this:
1 2 3
|
std::fstream open_for_read("file.txt", std::ios::in);
std::fstream open_for_write("file.txt", std::ios::out);
std::fstream open_for_read_and_write("file.txt", std::ios::in | std::ios::out); // Use the bitwsie OR operator or "pipe" to allow for different modes
|
It is more common to use the basic fstream objects:
1 2
|
std::ifstream open_for_read("file.txt");
std::ofstream open_for_write("file.txt");
|
Immediately after creating the object, it is good to check if it actually opened:
1 2 3 4
|
if(fstream_object)
{
// File exists and is ready for processing
}
|
Then when the file is open, you may extract or insert data using the bit shift operator, "<<" for output and ">>" for input, just like cout and cin:
1 2 3 4
|
std::string line = "Hello, World!";
fstream_object_out << line;
int my_var;
fstream_object_in >> my_var;
|
This will also work with user defined objects, providing you define how it should work:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class Account
{
private:
std::string name;
int balance;
public:
// This also works for cout and cin too!
inline friend std::ostream& operator<<(std::ostream& os, Account& a)
{
os << a.name << " " << a.balance;
return os;
}
inline friend std::istream& operator>>(std::istream& is, Account& a)
{
is >> a.name >> a.balance;
return is;
}
}
|
The last issue with oening files is of course, closing them. Most of the time this isn't a problem when you isolate your file manipulation because the destructor of the fstream objects closes them on destruction ( Going "out of scope" ) But, to be on the safe side:
And well.. that's all there is to it!
Hope this helped and good luck.
EDIT:
I copy and pasted so I can reuse for similar questions.