The cin
and cout
commands are for reading and writing to the stream for the console. However, there are other streams, and we can set one up for reading from a file.
Writing to a Text File
To write to a file, you will need to create a variable used to access the file stream. This data type is called an ofstream
(think output file stream). To use this data type, you will need to include the <fstream>
(file stream) header.
ofstream out;
out.open("numbers.txt")
out << 86 << 75 << 309 << endl;
out.close(); // necessary to ensure the data is written to the file
This will write the three numbers separated by spaces. Don’t forget to close the output file, as you want to ensure that the file is closed and written to before the program exits.
Reading from a Text File
Reading a text file is fairly simple. The biggest difference is you will use an ifstream
(input file stream) object instead of an output file object.
ifstream input;
int num1, num2, num3;
input.open("numbers.txt");
input >> num1;
input >> num2;
input >> num3;
input.close(); // close a file as soon as you can
cout << "The numbers read from the file are: "
<< num1 << num2 << num3 << endl;
Simple File IO in C++ was originally found on Access 2 Learn