Text File InputOutput


Text File Input/Output

This lecture discusses C++ file I/O. This will not be a complete discussion of the topic but only an introduction to illustrate the concepts. C++ handles I/O through what are called I/O streams. A stream produces or consumes data. Each stream is linked to a physical device through an object/variable and is manipulated by functions related to that object/variable.

The physical devices are treated the same and are considered "files". The "files" can be the keyboard, the monitor, a printer, RAM, an OS file etc. You should already know about I/O through the keyboard and the screen. The screen and keyboard I/O are handled by the data type streams: istream and ostream.

In this part of the lecture other types of data type streams for file handling are discussed: fstream, ofstream and ifstream. In C++ there are two kinds of files: Text or Binary. This lecture will only discuss Text Files.

The I/O streams are handled using objects of particular data types. Some of these data types and their corresponding functions are contained in the header iostream and you have been working with them already to provide screen and keyboard I/O. These objects/variables include: cout and cin and the functions include: >>, <<, getline( ) and get( ).

To provide for text files, the I/O streams data types require the inclusion of the header file fstream into the program. This header contains I/O objects (i.e. the data variables) and I/O functions that are not in the header iostream. The header fstream also includes the following I/O data types required to do text file I/O:

image from book

 ifstream // this stream is used for input of data only ofstream // this stream is used for output of data only fstream // this stream is used for both input and output of data 

image from book

Each of the above data types has two functions that are called constructors and they help to create the text I/O streams. These constructors define the I/O variable that will be used to handle the input or output. The constructors with arguments not only define the I/O variable but may also initialize it.

One of these constructors has a void signature and one has a signature that includes three arguments:

  • a Char string (i.e. the name of the file),

  • the mode (It determines what type of I/O will take place. This mode may be a default value or the programmer may specify a value)

  • a third argument used to help manage network file I/O.

The constructors are the following:

image from book

 ifstream() ifstream(char* filename, int mode = ios::in, int protect = filebuf::openprot) ofstream() ofstream(char* filename, int mode = ios::out, int protect = filebuf::openprot) fstream() fstream(char* filename, int mode, int protect = filebuf::openprot) 

image from book

 Note:  The equal signs above denote the fact that the programmer may specify a different value for the respective arguments or leave that argument blank and thereby get the default value that is listed. If the programmer leaves the argument blank, then the value specified as the rvalue will be the value assigned to the argument in question.

 Note:  If the first function in each case is used (i.e. ifstream( ), ofstream( ) and fstream( )) to define the I/O variable, then an additional function: open( ) must be used to open a connection between the program and the data file i.e. to initialize the I/O variable. The function open( ) would have the same arguments as those listed for the respective constructors above. The function open( ) is used to initialize the variable.

In the statements below, theFile is a variable defined of the respective data type and is initialized to act on the text file: TESTING.TXT. This exact variable name (i.e. theFile) is not required and any other variable name may be used instead. In addition, this name for the text file is also not a requirement and any text file name would work.

The variable theFile would be defined and initialized as a result of each of the following statements:

image from book

 ifstream theFile("TESTING.TXT"); ofstream theFile("TESTING.TXT"); fstream theFile("TESTING.TXT", theModeValue);                   // theModeValue is an int of a specific value. 

image from book

The constructor with no argument could be used to define the variable then the open( ) function can be used to initialize the variables in the following manner:

image from book

 ifstream theFile; .....             // several line of code later. theFile.open("TESTING.TXT"); 

image from book

or

image from book

 ofstream theFile; .....            //several lines of code later theFile.open("TESTING.TXT"); 

image from book

or

image from book

 fstream theFile; .....            //several lines of code later theFile.open("TESTING.TXT", theModeValue); 

image from book

In these last three examples, the first statement defines the variable theFile and then the second statement using the function open() initializes the variable theFile.

 Note:  There are several different options for theModeValue to include: ios::in, ios::out and ios::app. (The mode ios::app would permit the adding of data at the end of file. If ios::out was used instead, then any data that is currently in the file would be written over.) Although not apparent from the above examples, the mode for ifstream( ) and ofstream( ) have the default values ios::in and ios::out respectively (but these values can be overridden). For example the mode ios::app could be used to override the value ios::out when using ofstream().

The mode for fstream( ) must be specified. The mode for fstream( ) when working with text files can be any one of the following:

image from book

 ios::in ios::out ios::in | ios::out ios::app 

image from book

or

image from book

 ios::in | ios::app. 

image from book

The first mode above would imply input, the second would be for output and the third would be for both input and output. The fourth one would be for appending the data to the end of the file. The fifth option above would open the file for both input and for output that appends data at the end of the file. The binary OR operator: | is used when a mode for any of these functions may have several options. There is a lot more to this topic but the additional topics will not be discussed here.

Text File Output: An Example

To understand C++ file output see TEXTOUT.CPP In this example,

image from book

 ofstream outfile("TESTING.TXT") 

image from book

This statement tells the program to define the variable: outfile to be of data type ofstream and it is initialized to be used for output to the text file: TESTING.TXT. The word outfile could have been any variable name.

The following conditional:

image from book

 if(!outfile) {      cout << "File did not open." ;      exit(1); } 

image from book

is used in the program above to determine if there is a connection between the program and the data file. Should the connection fail, the statement "File did not open." should appear on the screen. The function exit( ) would cause the program to be exited without crashing and the value 1 would be sent to the operating system.

The following six lines of code:

image from book

 outfile << "This is a test of outputting text in line 1." << endl; outfile << "This is a test of outputting text in line 2." << endl; outfile << "This is a test of outputting text in line 3." << endl; outfile << "This is a test of outputting text in line 4." << endl; outfile << text << endl; outfile << "The number = " << aNumber; 

image from book

send the respective data lines to the data file in the same folder in which the program is located. These six lines should look like the ones that were used earlier with cout. Notice in particular that the variable text is output and the number aNumber would be output each as a stream of characters.

Copy this example into your C++ compiler, compile, link and run it. When you run it, you will create the file: TESTING.TXT on your computer in the same folder that contains the source file for the program and it will contain the following data that the program outputs to the file:

image from book

 This is a test of outputting text in line 1. This is a test of outputting text in line 2. This is a test of outputting text in line 3. This is a test of outputting text in line 4. This is a statement. The number = 125 

image from book

After you have run the program, go to the folder which contains the file: TESTING.TXT. Once you have located the file, double click it and the data file should appear inside of Notepad.

The example above illustrated how to output data to a text file.

Text File Input: An Example

Let's now look at a program that would input the same data from this text file. Look at TEXTIN.CPP and you will see code to input the same data that was output in the previous example.

In this program, notice that infile is defined as a variable of data type ifstream and initialized with TESTING.TXT:

image from book

 ifstream infile("TESTING.TXT"); 

image from book

The statement above would imply that infile could be used for input of data from the text file TESTING.TXT. Again the variable name infile could have been any name as with any variable for any data type (of course excluding keywords.)

The conditional: if(!infile) as in the previous example is used to test whether a connection has been made to the file TESTING.TXT.

Notice that the function get( ) is used in the code:

image from book

 infile.get(ch); while(infile) {   cout << ch;   infile.get(ch); } 

image from book

The function get( ) can be used with any stream variable of data type: istream, ifstream or fstream to input one character at a time.

The while( ) loop in the program is used to continue reading one character at a time from the data file and outputting it to the screen using the cout << ch; statement. In this while( ), the name of the variable infile is being used as a Boolean in the conditional. Should the file have no data or if there is no more data to be read, the conditional will be zero or in other words it would have the Boolean value of false. When this happens, the conditional will fail and the loop will be terminated.

Copy the above file to the same C++ project that contained TEXTOUT.CPP, compile and run it. Observer how this program inputs the data and then sends it to the screen that the program TEXTOUT.CPP sent to the data file.

In the example TEXTIN.CPP, the data was input one character at a time. It is also possible to input one field (i.e. one variable) at a time as well. Look at TEXTIN2.CPP. Copy this example to the same project and compare the program: TEXTIN2.CPP with the example TESTIN.CPP. Notice how each field in TEXTIN2.CPP is input. In C++ when working with text files, it is possible to read one character at a time, one field at a time or one record at a time.

In addition to using the operator >> for file input, it is also possible to use the functions, get() and getline();

 Note:  Although it was not done in the first two examples above, the files should be closed (as in the third example) when the program has finished with the files. This is done by using the function close() as in infile.close(); and this should be done as soon as the file has completed its objective. Some systems close the file as soon as the program ends but it is good practice to always close every file with the program code to prevent data loss. It is possible that if a file buffer has not emptied prior to the termination of the program, that the data in the buffer will be lost when the program terminates.

Appending Data to a Text File

Using the program: TEXTOUT.CPP run the program several times. After each running of the program, observe the contents of the file. Notice that even though the program was run several times, there is only one collection of data.

Now using the same project replace the statement:

image from book

 ofstream outfile("TESTING.TXT") 

image from book

with the following statement:

image from book

 ofstream outfile("TESTING.TXT", ios::app) 

image from book

After this change, run the program several times. After each run, note the contents of the file. Were the results different that before this change? What you should notice is that this time the data from each run was appended to the end of the previous data.

After you have run this modification, run the program TEXTIN.CPP in the sample project. Did this program display on the screen all of the data from each of the runs?




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

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