Q&A: File input and output with the fstream library

Table of Contents

1. File input

What library do you need to #include in order to have a file loader?

#include <fstream> - not ifstream or ofstream, remember!

When creating a file variable to read data from a text file, what data type should that variable be?

ifstream for Input File Stream

How do you open a text file for an input file stream?

ifstream input; // variable declaration
input.open( "filename.txt" ); // open a file

How do you check if loading the file failed?

if ( input.fail() )
{
  cout << "Couldn't find file!" << endl;
}

Give an example of how to read string and numeric data from a text file into variables in your program.

string text;
int number;
float price;

input >> number;
input >> price;

input >> text; // One word only, OR
getline( input, text ); // Notice it's like with cin, except our file variable.

Write down how to use a while loop to read in every word or every line of text from a text file.

string line;
while ( getline( input, line ) )
{
  cout << "Read line: " << line << endl;
}

2. File output

What library do you need to #include in order to write out to files?

#include <fstream>

When creating a file variable to write data to a text file with, what data type should the variable be?

ofstream for Output File Stream

What function is used to open a text file for an output file stream? Give some example code.

ofstream output;
output.open( "savegame.txt" );

Give an example of how to write some text and variable values to a file via an output file stream.

output << player.name << endl;
output << player.hp << endl;
output << player.gold << endl;

Author: Rachel Wil Sha Singh

Created: 2023-10-31 Tue 09:59

Validate