sábado, 16 de noviembre de 2013

Input/Output Streams

A stream is a flow of data.

  • Input stream: data flows into the program
    • cin
  • Output stream: data flows out of the program
    • cout
A stream variables must be declared before it can be used.  Must be initialized before it contains valid data.  They use special functions instead of the assignment operator to change values.

To declare a stream variable we defined the fstream library: #include <fstream>
To declare an input-file stream variable we use ifstream in_stream;
To declare an output-file stream variable we use ofstream out_stream;

Once a stream variable is declared, connect it to a file.  Connecting a stream to a file is opening the file.  We use the open function of the stream object: in_stream.open("infile.dat");


Once connected to a file, the input-stream variable can be used to produce input just as you would use cin with the extraction operator.  For example:

int one_number;
in_stream >> one_number;

An output-stream work similarly. For example:

ofstream out_stream;
out_stream.open ("outfile.dat");

out_stream << "one number = " << one_number << endl;

To close a file we use in_stream.close ( );  same to close the out_stream.
We close files to reduce the change of a file being corrupted if the program terminates abnormally.

Objects are special variables that have their own special purpose functions.  Is a variable that has function and data associated with it. (in_stream and out_stream)
A member functions is a functions associated with an object (the open function)

Object of different type have different member and different objects of the same type have the same member function.

Classes are a type whose variables are objects (ifstream in_stream;)

When a stream open functions fails. it is generally best to stop the program.  The functions exit, halts a program.  The exist function returns its argument to the operating system, they can causes program execution to stop and is NOT a member function.  Exit requires: #include <cstdlib>

Using fail and exit


To append new output to the end an existing file we use the constant ios::app
outStream.open("file.txt", ios::app);
If the file does not exist, a new file will be created.














No hay comentarios.:

Publicar un comentario