Introduction to Computer Science - C++
Writing a File
The following is a small program to write "bank records" to
a filed named "data.dat".
We have added the neccessary includes to use these functions.
We use the object of type ofstream (the o stands for output) since we want
to write this time.
To end the input the user must signify the end of file (eof)
by typing control-z in Windows©
or control-d in UNIX.
#include
using std::cout;
using std::cin;
using std::ios;
using std::cerr;
using std::endl;
#include
using std::ofstream;
#include
int main()
{
int account;
char name[40];
double balance;
// 1. Open the file "data.dat" for writing output (ios::out)
// creates an object I named ClientFile to be used to access the file
ofstream ClientFile( "data.dat", ios::out );
cout << " enter account number, name, balance. \n ^z or ^d to end \n";
while ( cin >> account >> name >> balance )
{
// 2. Write the variables into the file using ClientFile
ClientFile <
The following program reads and writes to a file.
Note that I used the "ios::out | ios::in" flags. The |
mean or, so the file is opened for reading or writing , or both.
Note also that I included more things. And I used an object
of type fstream not ifstream or ofstream. The fstream is the more
generic object type and can be used for writing or reading.
#include
using std::cout;
using std::cin;
using std::ios;
using std::cerr;
using std::endl;
#include
using std::ofstream;
using std::ostream;
using std::fstream;
using std::ifstream;
#include
int main()
{
int account;
char name[40];
double balance;
// 1. open for read/write
fstream ClientFile( "data.dat", ios::out | ios::in);
cout << " enter account number, name, balance. \n (eof (^Z) to end)";
while ( cin >> account >> name >> balance )
{
// 2. write to file
ClientFile <>account >> name >> balance)
{
// 5. example of a simple check you might use in a search for example
if (strcmp(name, "mary")==0)
{
cout << "I like the name Mary"<
Some other seek commands are:
- object.seekg(n, ios::beg); // n spaces beginning of file
- if no flag is specified, ios::beg is taken as the default
- object.seekg(n, ios::cur); // n spaces from current location in file
- object.seekg(n, ios::end); // n spaces back from end of file
- object.seekg(0, ios::end); // end of file
Use command rename("old", "newname") to rename the name of a file
or remove("filename")
© Nachum Danzig February 2006