Skip to main content
C++

File Streams in C++

By January 8, 2020No Comments
This section could have been better. While not terrible, it misses alot in the hopes of not being too lengthy or verbose (my guess). So far cout has been used in order to print things referenced by variables, ints or strings to the console. The “cout” functionality has been provided by the iostream standard library. Files can also be read by what is known as “file streams”. And for this another standard library called “fstream” is used. Therefore, to use “fstream” you need to include it in your program like so:
#include <fstream>
This library provides 3 objects for us to work this:
  1. ifstream: To read data FROM an input file stream.
  2. ofstream: To stream data TO an output filestream.
  3. fstream: Does both inputting and outputting. To read data from an input file and stream data to an output file.
Read from a file
Use the “ifstream” object
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    ifstream my_file;
    my_file.open("files/1.board");
    if (my_file) {
     cout << "The file stream has been created!" << "\n";
    }    
}
Explanation:
  1. Let’s assume the file to be read is called “1.board” and is within the “file” directory hence it’s path is “files/1.board”
  2. We’ve included the <fstream> ibrary in addition to other pre-processor directives like <iostream> (since we’re using cout) and <string> (since we’re using strings)
  3. Using the standard namespace
  4. Declare function int main()
    1. Within the body of the function make a new input file into which data will be streamed called my_file using the ifstream object
    2. Open the newly created file called my_file which is at the path files/1.board
    3. Files must be opened before you can read or write into them
    4. If my_file has been opened THEN
    5. print out the string “The file stream has been created!”
Read data from a file
getline method: The get line method reads line by line from an input stream. This method takes 2 parameters:
  1. ifstream object
  2. And a string to write the line to
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
    ifstream my_file;
    my_file.open("files/1.board");
    if (my_file) {
        cout << "The file stream has been created!" << "\n";
        string line;
        while (getline(my_file, line)) {
            cout << line << "\n";
        }
    }
}

Leave a Reply