![[Dept of Engineering]](http://www.eng.cam.ac.uk/images/house_style/engban-s.gif)
The following illustrates the use of putback() for an input stream. istreams also have an ignore function (is.ignore(5) would ignore the next 5 characters) and a peek() function which looks at the next character without removing it from the stream.
istream& eatwhite(istream& is)
{
char c;
while(is.get(c)) {
if (!isspace(c)) {
is.putback(c);
break;
}
return is;
}
}
The following illustrates the use of I/O to and from files. Given the name of 2 files on the command line (which are available to main as C-style character arrays), it does a file copy.
void error(string p, string p2="")
{
cerr<<p << ' ' << p2 << endl;
std::exit(1);
}
int main (int argc, char* argv[])
{
if (argc != 3) error("wrong number of arguments");
std::ifstream from(argv[1]);
if (!from) error("cannot open input file", string(argv[1]));
std::ofstream to(argv[2]);
if (!to) error("cannot open output file", string(argv[2]));
char ch;
while (from.get(ch)) to.put(ch);
if (!from || !to) error("something strange happened");
}
You can force the screen/file output to be up-to-date by using
cout.flush() or cout << flush;
but this isn't usually necessary.
If you want to write or read raw (binary) data (rather than strings that represent numbers) you can use write, read and casts (section 13) to keep the compiler happy. The following program writes 100 random integers into a file then reads them back.
[fontsize=\small,frame=single,formatcom=\color{progcolor}]
#include <iostream>
#include <fstream>
#include <cstdlib> // to use rand
using namespace std;
int main()
{
ofstream outfile("myresults",ios::out|ios::binary);
if (outfile.good() == false) {
cerr << "Cannot write to 'myresults'" << endl;
exit(1);
}
int num;
for (int i=0; i<100; i++){
num=rand();
outfile.write(reinterpret_cast<const char*>(&num), sizeof(num));
}
outfile.close();
ifstream infile("myresults");
if (infile.good() == false) {
cerr << "Cannot open 'myresults'" << endl;
exit(1);
}
int count=0;
while(infile.read(reinterpret_cast<char*>(&num), sizeof(num))) {
cout << num << endl;
count++;
}
cout << count << " numbers read in" << endl;
infile.close();
return 0;
}