File Input/Output

The next thing we're going to learn is how to input/output data from/to files. This is a great thing to learn for lots of reasons.

Syntax

We are interested in two classes here. The ofstream class handles outputting data from your program to a data file (ofstream stands for output file stream). The ifstream class handles inputting data from a file to your program (ifstream = input file stream). To use these classes you must #include<fstream>.

You can find the full documentation for ofstream and ifstream on the c++ reference page.

ofstream
ifstream

Below is a quick summary of how to use each class.

The ofstream class

To write data to a file, first declare an ofstream object.

    ofstream outputStream;

Afterwards, open the file that you plan to write to

// Method #1
    outputStream.open("myFile.txt");

// Method #2
    string fileName;
    // initialize fileName here
    outputStream.open(fileName);  // some compilers require you to write 'filename.c_str()', instead. Not sure why...

Just to be careful, check if your file opened correctly

    if(!outputStream.is_open()) {
        // This means your file didn't open. Give some error message?
    }

Now you can write data to your file. The syntax is the exact same as for cout, just use the name of your ofstream instead of cout.

    outputStream << "Hello world!" << endl;  // will write Hello World! to your file
                                             // and put an endline afterwards

Close your file when you are done writing data.

    outputStream.close();

Here's a full example program:

#include<fstream>
#include<string>
#include<iostream>
using namespace std;

int main() {
    ofstream outputStream;
    
    const string fileName = "testFile.txt";

    outputStream.open(fileName);
    if(!outputStream.is_open()) {
        cout << "File failed to open! Exiting program.";
        return 0;
    }
    outputStream << "Hello world!" << endl;  // will write Hello World! to testFile.txt
    outputStream.close();

    return 0;
}

Notes:

The ifstream class

ifstream and ofstream have a lot in common, so the summary for ifstream looks a lot like the summary for ofstream.

To read data from a file, first declare an ifstream object.

    ifstream inputStream;

Afterwards, open the file that you plan to read from

// Method #1
    inputStream.open("myFile.txt");

// Method #2
    string fileName;
    // initialize fileName here
    inputStream.open(fileName);

Just to be careful, check if your file opened correctly

    if(!inputStream.is_open()) {
        // This means your file didn't open. Give some error message?
    }

Now you can read data from your file. The syntax is the exact same as for cin, just use the name of your ifstream instead of cin.

    int temp;
    inputStream >> temp;

Close your file when you are done writing data.

    inputStream.close();

Here's a full example program:

#include<fstream>
#include<string>
#include<iostream>
using namespace std;

int main() {
    ifstream inputStream;
    
    const string fileName = "testFile.txt";

    inputStream.open(fileName);
    if(!inputStream.is_open()) {
        cout << "File failed to open! Exiting program.";
        return 0;
    }
    
    string temp;
    inputStream >> temp;  // try getline(inputStream, temp) here too
    inputStream.close();

    cout << "I read from your file and got " << temp << endl

    return 0;
}
Notes:

Longer Example: Counting words inside a large text

Alright, here's the plan. We're going to write a program that looks through a text file, and tells you how many times a certain word appears. Here's a rough outline of the program.

Here is the final code.

WordCount.cpp

We're going to test this on the text of Harry Potter 1. I'm pretty sure it's illegal for me to link that here, so if you want to do this at home you're going to have to find your own text file. (googling "Harry Potter 1 as txt" should be good enough)

Longer Example: Check if a number is prime

Setup: Create a file that stores a bunch of primes (all primes between 0 and some max-value)

I wrote some code that finds all primes between 0 and MAX_VALUE (here MAX_VALUE is a constant specified at the beginning of the code), and saves the results in a file called "primes.txt". I think we're only going to briefly explain how this works in class (no heavy details). The coding isn't very complicated, but it involves more math than I want to use in PIC10A.

findPrimes.cpp

The actual problem: Check if a number is prime

This program is going to use the "primes.txt" that we just created. This program will test if a number is prime by checking to see if it is divisible by the prime numbers we found in the previous program.

This one we will code ourselves if we have time. If we run out of time then we'll just play around with the finished code.

isPrime.cpp