Chapter 6
In this chapter, you will learn about: Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance
Streams and Basic File I/O I refers to the program Input O refers to program Output: I/O means program Input/Output Examples of Input Devices Keyboard File Your program reads input from an Input Device via a stream object Examples of Output Devices Monitor File Your program writes to an Output Device via a stream object
Streams and Basic File I/O A stream is a flow of data. Input stream: Data flows into the program From keyboard, if the input stream is logically connected to the keyboard From a file, if the input stream is logically connected to the file Output stream: Data flows out of the program To the monitor screen, if the output stream is logically connected to the screen To a file, if the output stream is logically connected to the file
Streams Keyboard and Screen Pre-defined streams cin Input stream connected to the keyboard cout Output stream connected to the screen cin and cout are defined in the iostream library Use #include <iostream> in your program You can declare your own streams to use with files.
Streams Files User-defined streams You can define streams to: Read from files (for convenience) Get input from a file Write to files (for persistent storage even after program terminates!) Send output to a file
Streams and Basic File I/O Streams A Stream is a Special type of Variable known as an Object Special kind of Variable (Object)? A Stream variable cannot be used in an assignment statement (unlike: int, double, float, char..) An Object is a special variable associated with a one or more special-purpose functions [We will talk about this shortly]
Stream and Basic File I/O Streams A variable of type Stream, must be: declared before it can be used initialized before it contains valid data By connecting the stream variable to a file Using special-purpose functions Conceptually, the initialized value is the file it is connected to So How do you change its initialized value? By disconnecting from one file and connecting to another file Using special-purpose functions
Input File Stream Variable Declaration Input File Stream Type is: ifstream Declaration involves Two main steps: 1. First, specify following directives: #include <fstream> // include the fstream library using namespace std; 2. Now, declare the stream variable as type ifstream: ifstream in_stream; // in_stream is the input stream variable // name of your chosen
Output File Stream Variable Declaration Output File Stream Type is: ofstream Declaration involves Two main steps: First, specify the following directives: #include <fstream> // includes the fstream library using namespace std; Now declare the ofstream variable: ofstream out_stream; // out_stream is a name of the output stream // variable of your choice
Input Streams Connecting to a File Assuming stream variable is declared, you may now connect the stream variable to the file: To connect the input stream (in_stream) to a file, you open the file: in_stream.open("infile.txt"); Quotes Input stream variable name Special-purpose function File name in the C++ program folder Mandatory period
Input Streams Getting Data from a File Once you have declared the input stream variable (in_stream) and connected the stream to a file, your program can use the input stream variable to read data from the file: Example: Read two input numbers from the file infile.dat and store them in the integer variables first_num, second_num ifstream in_stream; in_stream.open( infile.dat"); int first num, second_num; in_stream >> first_num >> second_num;
Output Streams Connecting to a File Assuming the output stream variable is declared, you may now connect the output stream variable to the file: To connect the output stream variable (out_stream) to a file, you open the file: out_stream.open( outfile.dat"); Quotes Output stream variable name Special-purpose function External File name in the C++ program folder Mandatory period
Output Streams Writing Data to a File Once you have declared the output stream variable (out_stream) and connected the stream to a file, your program can use the input stream variable to write data to a file: Example: Write two numbers from integer variables: first_num and second_num to the file outfile.dat ofstream out_stream; out_stream.open("outfile.dat"); out_stream << First Number = " << first_num << Second Number = " << second_num;
Disconnect Streams Closing the File Your Program should close the File after usage Why? To disconnect the stream from the file What happens if you fail to close the file? File may get corrupted if program terminates abnormally The OS will close the file if the program ends normally
Closing File Syntax To close the input file: in_stream.close( ); To Close the Output file: out_stream.close( );
Intro to Classes and Objects Objects Examples of Object Streams: in_stream, out_stream, cin, cout An Object: A variable that has one or more functions as well as data associated with it Can you list some of the functions associated with the stream objects? Let s analyze the open functions associated with types: ifstream and ofstream
Intro to Classes and Objects Member Functions A function associated with an object is a Member Function The open function is a member function of in_stream, which is of type ifstream But the open function is also a member function of out_stream, which is of type ofstream The two member functions are different One opens a file for input The other opens the file for output
Objects Member Function Names Objects of different types have different member functions Some of these member functions might have the same name Different objects of the same type have the same member functions
Classes A type whose variables are objects, is a class ifstream is the type of the in_stream variable (object) Therefore ifstream is a class The class of an object determines its member functions Example: ifstream in_stream1, in_stream2; ofstream out_stream1, out_stream2; in_stream1.open and in_stream2.open are the same function out_stream1.open and out_stream2.open are the same function, but different from the functions in in_stream1.open and in_stream2.open
Class Member Function Member functions of an object are the member Functions of its class The class determines the member functions of the object The class ifstream has an open function Therefore, every object declared of type ifstream has that open function
Calling_Object.Member_Function_Name(Argument_List); Examples: in_stream.open( infile.dat ); out_stream.open( outfile.dat ); Note: You must specify the object containing the member function The calling object must be separated from the member function by the dot operator
Opening a file could result in Failure: If the file does not exists If the name is incorrectly typed Error message may or may not be generated Success: How do you handle Opening File Failures?
Use the member function fail( ) to test the success of a stream operation fail returns true if the stream operation failed false if successful What do you do when the program catches Stream Errors: Good idea to automatically stop (exit) the program execution
To exit a program, use the function call: exit( ) You must precede the function call with: #include <cstdlib> using namespace std;
Use both member function fail and the function call exit( ) immediately after calling the member function open in_stream.open( infile.dat"); if( in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1) ; } Return to OS: Convention: Use1 for failure 2 for Success
! When you read from a file, you program should NOT: Generate prompts Echo values read Why? Example Program Reads from Keyboard cout << Enter the number: ; cin >> the number; cout << The number you entered is << the_number Example Program Reads from File ifstream infile; infile >> the_number; The input file must contain the expected data item(s)
"# So far.. Our member function open Creates a new file for output if file name does not exists Overwrites the existing file if it exists What if you wish to append the output to an existing file: important.txt? Use the constant ios::app in the member function open ofstream outstream; outstream.open("important.txt", ios::app); You must include the iostream library priori to this call #include <iostream> If the file does not exist, a new file will be created Why?
"# #include <fstream> #include<iostream> int main() { using namespace std; cout << opening data.txt for appending.\n ; ofstream fout; fout.open( data.txt, ios::app); if (fout.fail() ) { cout << Input file opening failed.\n ; exit(1); } fout << 5 6 pick up sticks.\n << 7 8 ain t C++ great!\n ; fout.close(); cout << End of appending to file.\n return 0; } Original data.txt file 1 2 buckle my shoes. 3 4 shut the door. data.txt file (After Program execution) 1 2 buckle my shoes. 3 4 shut the door. 5 6 pick up sticks. 7 8 ain t C++ great!
$ % Sometimes it is convenient to let the user enter the correct I/O filename from the keyboard Your program should be able to read the text string entered from the key board into a string variable: A text string is a simply sequence of characters How do you declare a variable (my_file) to hold a sequence of 15 characters? char myfile[16]; Precede the declaration with the directive: #include<string>
&' ( $ char my_file[16]; cout << "Enter the file_name "; cin >> my_file; ifstream in_stream; in_stream.open(my_file); if (in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1); }
( Use commands to format the output to Files: The number of spaces between items The number of digits after the decimal point The numeric style: scientific notation for fixed point Show digits after a decimal point Show plus signs in front of positive numbers Left or right justify numbers in a given space
( Output to Screen cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); Output to File ofstream out_stream; out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2);
& precision is a member function of class ofstream The Output Following out_stream.precision(2); A total of 2 significant digits 23. 2.2e7 2.2 6.9e-1 0.00069 OR 2 digits after the decimal point 23.56 2.26e7 2.21 0.69 0.69e-4 Calls to precision apply only to the stream named in the call: out_stream
&()&(*+ setf is a member function of class ofstream setf is an abbreviation for set flags A flag is an instruction to do one of two options ios::fixed is a flag The Output Following out_stream.setf(ios::fixed); All floating point numbers Will be written in fixed-point notation, the way we normally expect to see numbers Unsets scientific notation (ios::scientific) Calls to setf apply only to the stream named in the call: out_stream
&()&(*+ setf is a member funtion of class ofstream ios::scientific is a flag The Output Following out_stream.setf(ios::scientific); All floating point numbers Will be written in scientific notation Unsets fixed-point notation (ios::fixed) Calls to setf apply only to the stream named in the call: out_stream
&()&,*+ setf is a member function of class ofstream setf is an abbreviation for set flags The Output Following out_stream.setf(ios::showpoint); All floating point numbers Will show the decimal point even if the trailing digits are zero Calls to setf apply only to the stream named in the call: out_stream
Use the member function width of class ofstream: Example Print number 8 in four spaces ofstream out_stream; out_stream.width(4); cout_stream << 8<< endl; The member function call affects only the trailing output statements
-('.( Left Justified Print number 8 in four spaces and left justified Right Justified Print number 8 in four spaces and right justified ofstream out_stream; out_stream.width(4); cout.setf(ios::left) cout_stream << 8<< endl; ofstream out_stream; out_stream.width(4); cout.setf(ios::right) cout_stream << 8<< endl; Unsets flag ios::right Unsets flag ios::left