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 <iostream> using std::cout; using std::cin; using std::ios; using std::cerr; using std::endl; #include <fstream> using std::ofstream; #include <cstdlib> 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 <<account<<' '<<name <<' ' <<balance<<'\n'; cout<<":"; } return (1); }

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 <iostream> using std::cout; using std::cin; using std::ios; using std::cerr; using std::endl; #include <fstream> using std::ofstream; using std::ostream; using std::fstream; using std::ifstream; #include <cstdlib> 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<<'\n'; cout<<":"; } cout<< "now we read the file\n"; // 3. seekg() function lets me move back to the beginning of the file ClientFile.seekg(0); // 4. read the data from ClientFile while (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"<<endl; } // 6. print the data cout << "account number "<<account << " name " <<name <<" balance "<<balance<<endl; } return (1); }

Some other seek commands are:

Use command rename("old", "newname") to rename the name of a file
or remove("filename")

© Nachum Danzig February 2006