Fstream File Input and Output in C++

Dr. Lawlor, CS 202, CS, UAF

First, I need to say a little about how files work in NetRun.

They don't.

That is, you can't (currently) do any of these in NetRun:
Sorry.  What you can do, though:
I've written a tiny utility function for NetRun called "cat(filename);" (from the UNIX utility named cat) that reads and displays the contents of the file you give it.  It will tell you the length of the file too, and give you an error message if the file does not exist.

Here I create a file with some simple data in it, and print the file:
fstream f;
f.open("ted",ios::out); // make a file "ted"
f<<"Excellent!\n"; // write some data to it
f.close(); // be sure to close it afterwards!

cat("ted");

(Try this in NetRun now!)

(Note: it is important to close the file before calling cat.  If the file is still open, "f" may have cached some of your output in its internal buffers, and "cat" will tell you the file is empty.)

Here I'm trying to print a file that doesn't exist:
cat("totallythere");

(Try this in NetRun now!)

Here I'm printing out the binary executable "code.exe" (or at least the first 1000 bytes) :
cat("code.exe");

(Try this in NetRun now!)

Operations on an fstream

Here's a non-exhaustive list of what you can do with an fstream object:
The possible access modes are:
For example, here we're writing some string data, and then reading some of it back in:
fstream f,g;
f.open("ted",ios::out); // make a file "ted"
f<<"Party on!\n"; // write some data to it
f.close(); // be sure to close it afterwards!

g.open("ted",ios::in); // reopen file
std::string s;
g>>s;
if (g) cout<<"Read from file: '"<<s<<"'\n";
else cout<<"Couldn't read from file...\n";
g.close();

cat("ted");

(Try this in NetRun now!)