=====
CS 111 - Week 14 Lecture 2 - 2024-12-05
=====
=====
TODAY WE WILL:
=====
* announcements
* finish function get_smallest
* intro file input/output
* prep for next class
=====
* should be wrapping up Homework 11!
* at-least-1st-attempts are due by 11:59 pm tomorrow,
Friday, December 6
=====
intro to stream-based file input/output in C++
=====
* we have been using the stream objects cin and cout
from the C++ iostream library to do interactive input
and screen output
* C++ also has a library fstream to support stream-based
file input/output
SO, Step 1: to use this fstream library,
#include it in the .cpp file whose function(s) use it!
(before the using namespace std;)
#include <fstream>
* The iostream library could assume many users want
standard input and output, and could declare and create
the objects cin and cout accordingly
BUT the fstream library can't know how many files you want
to do things to/with -- you've got to declare your
file stream objects yourself;
* IF you want to read FROM a file,
(like cin reads from the keyboard/standard input),
you declare an INPUT file stream object to connect to
this file to do this input
The type of this object: ifstream
ifstream my_fin;
* IF you want to write TO a file,
(like cout writes to the screen/standard output),
you declare an OUTPUT file stream object to connect to
this file to do this output
The type of this object: ofstream
ofstream my_fout;
* fstream objects (whether they are ifstream objects or
ofstream objects) have a method open
to connect the file stream TO a desired file,
and to open that stream for the desired action
One version of the open method expects one argument,
a name of a desired file written as a string,
(a full path or its name from the current folder)
and it tries to connect the calling file stream to
that file
* for an ifstream, calling open connects the ifstream
to that file so the stream is ready to read its
1st character:
my_fin.open("desired_input.txt");
* for an ofstream, calling open creates a file with its
argument name if that file does not yet exist,
(and connects to the existing file and DELETES its
current contents if it does exist!!),
so the stream is ready to write its 1st character
my_fout.open("desired_output.txt");
* ONCE you have an open ifstream,
read from it like you read interactive input using cin!
int quant;
my_fin >> quant;
ONCE you have an open ofstream,
write to it like you write screen output using cout!
my_fout << "Howdy" << endl;
* WHEN you are done with a file stream object,
it is considered GOOD PRACTICE to close that file stream
with its close method (which expects no arguments)
my_fin.close();
my_fout.close();
(and you HAVE to do this if you wish to connect a different
file stream to the same file later in your function,
since a file can only have one file stream connected to it
at a time)