* for simple file input/output, you can use
C++'s fstream library
#include <fstream>
* how do you declare your own
input file stream or output file stream?
an input file stream is of type:
ifstream
an output file stream is of type:
ofstream
* ifstream in_stream;
* ofstream out_stream;
* you then need to connect your
ifstream or ofstream TO a file,
using the ifstream or ofstream
open method;
* this method expects the name
of your file (relative
to your current working
directory OR where this
program is running)
EXPRESSED AS A char* STRING!
(by the way,
you can get a char* version
of a true string object
using its c_str() method...)
string junkfile;
cout << "what file?" << endl;
cin >> junkfile;
ifstream in_stream;
in_stream.open(junkfile.c_str());
* once you have opened an ifstream,
say it is called in_stream,
you can read something from it
using >> like you did using cin:
int next_val;
in_stream >> next_val;
* once you have opened an ofstream,
say it is called out_stream,
you can write to that stream
like you did to cout:
out_stream << "mooooo";
* AND, for GOOD STYLE,
what you have opened, you should close;
when you are done with a file stream,
close it with its close method:
in_stream.close();
out_stream.close();
* side note 1:
* there is a file stream method
called fail that expects no
arguments by returns true if
an open just failed;
in_stream.open(junkfile.c_str());
if (in_stream.fail())
{
cout << "Sorry, cannot open "
<< junkfile << endl;
return EXIT_FAILURE or something;
}
* what if you'd like to read until you
reach the end of file?
There is a VERY PERSNICKETY method eof
that expects no arguments and returns
true if you have reached the end of
a file that you are reading from
...BUT!! you need to "prime" eof with
at least one attempted read
(a read essentially needs to fail
for eof to know the end is reached...!)
FORTUNATELY, we know the sentinel-controlled
loop pattern:
string thing;
in_stream >> thing;
while (in_stream.eof() == false)
{
cout << "hey, I read: "
<< thing
<< endl;
in_stream >> thing;
}
* you can use getline to read a whole
line -- it expects an input stream as
its first argument and a string to assign
to as its second argument,
and has the side effect of reading the
next line read to that string;
CAVEAT:
if you go from reading using
>>
TO
getline,
you need an "extra" call to getline to
get past the last enter before
the line you really want...!
my_in_stream >> quantity;
string ignore_me;
getline(my_in_stream, ignore_me);
string what_i_want;
getline(my_in_stream, what_i_want);