Engineering Forum

India Education

Engineering Colleges Forum

Files and Streams part 2

This is a discussion on Files and Streams part 2 within the Computer engineering forums, part of the ENGINEERING WORLD category; Character Input and Output Input using "get(...)" Having opened an input file, we can extract or read single characters from ...


Go Back   Engineering Forum > ENGINEERING WORLD > Computer engineering

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

   

Reply

 

Thread Tools Display Modes
  #1 (permalink)  
Old 08-28-2008, 07:26 PM
aayush_005's Avatar
Administrator
 
Join Date: Aug 2008
Posts: 225
Default Files and Streams part 2

Character Input and Output
Input using "get(...)"

Having opened an input file, we can extract or read single characters from it using the member function "get(...)". This function takes a single argument of type "char". If the program is in the state represented in Figure 4.2.1, the statement
in_stream.get(ch);

has two effects: (i) the variable "ch" is assigned the value "'4'", and (ii) the ifstream "in_stream" is re- positioned so as to be ready to input the next character in the file. Diagramatically, the new situation is:


Figure 4.4.1
Output using "put(...)"

We can input or write single characters to a file opened via an ofstream using the member function "put(...)". Again, this function takes a single argument of type "char". If the program is in the state represented in Figure 4.2.2, the statement
out_stream.put('4');

changes the state to:


Figure 4.4.2
The "putback(...)" Function

C++ also includes a "putback(...)" function for ifstreams. This doesn't really "put the character back" (it doesn't alter the actual input file), but behaves as if it had. Diagramatically, if we started from the state in Figure 4.4.1, and executed the statement
in_stream.putback(ch);

we would end up in the state:


Figure 4.4.3

Indeed, we can "putback" any character we want to. The alternative statement
in_stream.putback('7');

would result in:


Figure 4.4.4
(BACK TO COURSE CONTENTS)



4.5 Checking for the End of an Input File
4.5.1 End-of-file Checking For Systems Which Implement "eof()"

Special care has to be taken with input when the end of a file is reached. Most versions of C++ (including GNU g++ and Microsoft Visual C++) incorporate an end-of-file (EOF) flag, and a member function called "eof()" for ifstreams to test if this flag is set to True or False. It's worth discussing such systems briefly, since many text books (including Savitch) assume this useful facility.

In such systems, when an ifstream is initially connected to a file, the EOF flag is set to False (even if the file is empty). However, if the ifstream "in_stream" is positioned at the end of a file, and the EOF flag is False, the statement
in_stream.get(ch);

will leave the variable "ch" in an unpredictable state, and set the EOF flag to True. Once the EOF flag is set to True, no attempt should be made to read from the file, since the results will be unpredictable. To illustrate with a diagramatic example, if we start from


Figure 4.5.1

and then execute the statement
in_stream.get(ch);

this results in the state


Figure 4.5.2

If we again execute the statement
in_stream.get(ch);

this now results in the state


Figure 4.5.3

The boolean expression
in_stream.eof()

will now evaluate to True.

Below is a simple program which uses these techniques to copy the file "Lecture_4" simultaneously to the screen and to the file "Copy_of_4". Note the use of a while loop in this program. "While" loops are simplified versions of "for" loops, without the initialisation and update statements in the "()" parentheses (we will look at such statements again in the next lecture).
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
char character;
ifstream in_stream;
ofstream out_stream;

in_stream.open("Lecture_4");
out_stream.open("Copy_of_4");

in_stream.get(character);
while (!in_stream.eof())
{
cout << character;
out_stream.put(character);
in_stream.get(character);
}

out_stream.close();
in_stream.close();

return 0;
}
Program 4.5.1
(BACK TO COURSE CONTENTS)



4.6 Streams as Arguments in Functions

Streams can be arguments to functions, but must be reference parameters (not value parameters). Below is another version of Program 4.5.2 which uses the function "copy_to(...)".
#include <iostream>
#include <fstream>

using namespace std;

void copy_to(ifstream& in, ofstream& out);

/* MAIN PROGRAM: */
int main()
{
ifstream in_stream;
ofstream out_stream;

in_stream.open("Lecture_4");
out_stream.open("Copy_of_4");
copy_to(in_stream, out_stream);
out_stream.close();
in_stream.close();

return 0;
}
/* END OF MAIN PROGRAM */

/* FUNCTION TO COPY A FILE TO ANOTHER FILE AND TO THE SCREEN: */
void copy_to(ifstream& in, ofstream& out)
{
char character;

in.get(character);
while (!in.eof())
{
cout << character;
out.put(character);
in.get(character);
}
}
/* END OF FUNCTION */
Program 4.6.1
(BACK TO COURSE CONTENTS)



4.7 Input and Output Using ">>" and "<<"

So far we have only talked about writing and reading individual characters to and from files. At the lowest level, ofstreams and ifstreams only deal with files which are sequences of characters. So data of other types ("int", "double", etc.) has to be converted into character sequences before it can be written to a file, and these character sequences have to be converted back again when they are input.

However, the operators ">>" and "<<", which we have already met in the context of keyboard input and screen output, do some of this conversion automatically. For example, from the state


Figure 4.7.1

execution of the statement
out_stream << 437 << ' ';

will result in the new state


Figure 4.7.2

When using these higher level facilities, it is important to include at least one ' ' (blank) character (or a new-line character) after each item of data written. This ensures that the data items are correctly separated in the file, ready for input using ">>". For example, from the state


Figure 4.7.3

where "n" has been declared as of data type "int", execution of the statement
in_stream >> n;

will result in the new state


Figure 4.7.4

Notice that the operation ">>" has skipped over the blank space "' '" before the number 437. It always does this, no matter what data type it has been reading or expects to read (even characters).

The following program, which first creates a file called "Integers" containing the integers 51, 52, 53, 54 and 55, further illustrates these techniques.
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
char character;
int number = 51;
int count = 0;
ofstream out_stream;
ifstream in_stream1; /* Stream for counting integers. */
ifstream in_stream2; /* Stream for counting characters. */

/* Create the file */
out_stream.open("Integers");
for (count = 1 ; count <= 5 ; count++)
out_stream << number++ << ' ';
out_stream.close();

/* Count the integers in the file */
in_stream1.open("Integers");
count = 0;
in_stream1 >> number;
while (!in_stream1.eof())
{
count++;
in_stream1 >> number;
}
in_stream1.close();
cout << "There are " << count << " integers in the file,\n";

/* Count the non-blank characters */
in_stream2.open("Integers");
count = 0;
in_stream2 >> character;
while (!in_stream2.eof())
{
count++;
in_stream2 >> character;
}
in_stream2.close();
cout << "represented using " << count << " characters.\n";

return 0;
}
Program 4.7.1

This program produces the following output:
There are 5 integers in the file,
represented using 10 characters.

Once again, notice that, unlike the function "get(...)", the operator ">>" has jumped over the blank (i.e. space) characters in the file (which separate the five integers) when used in counting characters in the last part of the program.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are Off
Refbacks are Off
Forum Jump


All times are GMT. The time now is 04:39 AM.


Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.