Writing to a File

You output or write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.

The following program writes information inputted by the user to a file named students.dat, which is created if it does not already exist.

 #include <fstream> #include <iostream> using namespace std; int main () {  char data[80];  ofstream outfile;  outfile.open("students.dat");  cout << "Writing to the file" << endl;  cout << "===================" << endl;   cout << "Enter class name: ";   cin.getline(data, 80);  outfile << data << endl;  cout << "Enter number of students: ";   cin >> data;  cin.ignore();  outfile << data << endl;  outfile.close();  return 0; } 

The input and output could be

 Writing to the file =================== Enter class name: Programming Demystified Enter number of students: 32 

Open the file in a plain-text editor such as Notepad. The contents with the preceding sample input would be as follows :

 Programming Demystified 32 

The statement that wrote to the file included the endl keyword:

 outfile << data << endl; 

The reason is to write the name of the class (Programming Demystified) to a different line than the number of students, 32. Otherwise, the file contents would be

 Programming Demystified32 

The call to the ignore member function after cin >> data follows the advice in Chapter 12 to clear the newline character from the input buffer after using the cin object with the stream extraction operator ( >> ).

You instead could have used an fstream object to write to the file. You would have changed the data type of outfile from ofstream to fstream and then changed the call to the open method to include two arguments:

 fstream outfile;  outfile.open("students.dat", ios::out); 

Alternatively, you could have used the fstream constructor:

 fstream outfile ("students.dat", ios::out); 

If you want to append, you only need to add an ios:app flag to the second argument of the constructor or the open member function using the bitwise or operator ().

C++ Demystified(c) A Self-Teaching Guide
C++ Demystified(c) A Self-Teaching Guide
ISBN: 72253703
Year: 2006
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net