fstream is another library you can include at the top of your program which will allow you to open, read, and write files. You will be introduced to two new data types known as
ifstream and
ofstream, which allow for opening a file for reading, and opening a file for writing respectively. The best way to tell is by an example(s).
Reading in from a file
Let's say we have a file called "test.txt":
i
File (text.txt)
This is a test
And let's say we have the following C++ program:
Code (C++)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string str1, str2;
ifstream fp; //Initialise ifstream class
fp.open("test.txt"); //Tell it to open "test.txt" for reading
fp >> str1 >> str2; //Read first two words into "str1" and "str2"
fp.close(); //Close the file
cout << str1 << endl;
cout << str2 << endl;
}
Simple enough, the file will be opened into the program and the first
word will be read. This will be the output:
Output
This
is
To put it simply: To the fstream library, a
word is defined as a constant sequence of characters until broken by a space, or newline. It started at the beginning of the file, and read until there was a space. That is when it decided to stop reading in.
Writing to a file
Let's write a program that loops from 0 to 99, and prints it to the console. It is just a simple for loop, no?
Code (C++)
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 100; i++) {
cout << i << endl;
}
}
If you don't know what this does, please do previous labs first. This loop prints out values from 0 to 99, as planned. What could we do to write them to a file? This is where the
ofstream comes in:
Code (C++)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream op;
op.open("output.txt"); //Opens file for writing
for (int i = 0; i < 100; i++) {
op << i << endl; //Writes each number to each line
}
op.close(); //Closes the file
}
This code will produce a file called "output.txt" which has 100 lines counting from 0 to 99.
Similarities with cin and cout
If you noticed,
ifstream acts exactly like how cin works with your input. It shouldn't surprise you then, that ofstream works the same as cout, except it is targeting a file. Because of this, you are more than welcome to utilise
iomanip on ofstreams and they will work as planned.
Hint: You will do that in this lab.