file input and output in c++. keyboard and screen i/o #include cin (of type istream) cout (of type...
Post on 03-Jan-2016
255 Views
Preview:
TRANSCRIPT
File Input and Output in C++
Keyboard and Screen I/O
#include <iostream>
cin
(of type istream)
cout
(of type ostream)
KeyboardScreen
executingprogram
input data output data
2
File I/O
#include <fstream>
stream variable(of type ifstream)
Input.txt Report.txt
executingprogram
input data output data
3
stream variable(of type ofstream)
File I/O Statements#include <fstream>
// Declare File Streamsifstream myInfile; // for input
ofstream myOutfile; // for output
myInfile.open(“myIn.dat”); // Open input filemyOutfile.open(“myOut.dat”); // Open output file
// Use file streams for input and output
// Close filesmyInfile.close();myOutfile.close();
4
File Stream Variables
File Streams are Variables cin and cout are automatically created
You must declare your own stream variables to use file I/O
For Input… Variable type is “ifstream” (input file stream)
For Output… Variable type is “ofstream” (output file stream)
Opening a File
Opening a file Associates your file stream variable with the
external (disk) name for the file If the input file does not exist on disk, open
is not successful (fail state!) If the output file does not exist on disk, a
new file with that name is created If the output file already exists, it is erased!
stream_name.open( “file_name” );
6
REMEMBER!
File input and output streams work exactly the same as cin and cout You can use the same input commands
>>, get, getline, etc… You can use the same output commands and
modifiers <<, endl, fixed, showpoint, setprecision, setw, etc…
Simply replace cin or cout with your custom declared stream variable
SYNTAX
These examples yield the same result.
fileIn >> length;
fileIn >> width;
fileIn >> length >> width;
Input Statements
ifstream fileIn;fileIn.open(“myFile.txt”);fileIn >> Variable >> Variable . . .;
8
STATEMENTS CONTENTS POINTER POSITION
int i; 25 A\n char ch; 16.9\n float x; fileIn >> i; 25 A\n
16.9\n
fileIn >> ch; 25 A\n 16.9\n
fileIn >> x; 25 A\n 16.9\n
Another example using >>
i ch x
25
25 ‘A’
i ch x
i ch x
i ch x
16.925 ‘A’
NOTE: shows the location of the buffer pointer
9
Common Input mistake
• You open the file stream infile for input
• But then your input statements are for CIN
• You didn't print a prompt since you shouldn't need one - you're reading from a FILE
• The program appears to "hang" because it is waiting for KEYBOARD input! there's no prompt so you don't know it's waiting
File Output
When a file is opened using an ofstream object, any output inserted into that stream is placed into the file buffer rather than on the screen
HINT: the contents of the output file will appear exactly as it would have appeared if it were placed on the monitor first try the output using cout to verify it once it is to your liking, change the stream name to
your output file
Output StatementsSYNTAX
These examples yield the same output
fileOut << “The answer is “;
fileOut << 3 * 4;
fileOut << “The answer is “ << 3 * 4;
ofstream fileOut;fileOut.open(“outfile.txt”);fileOut << Expression << Expression . . .;
Run Time File Name Entry
#include <string>// Contains conversion function c_str
ifstream inFile;string fileName;
cout << “Enter input file name: “ << endl; // Promptcin >> fileName;
// Convert string fileName to a C string typeinFile.open(fileName.c_str());
13
If you do not know up front what the name of the file to open will be, you can have the user enter the file name at the keyboard into a string.
Stream Fail State
When a stream enters the fail state, Further I/O operations using that stream have no
effect at all The computer does not automatically halt the
program or give any error message!! Possible reasons for entering fail state include
Invalid input data (often the wrong type) Opening an input file that doesn’t exist Opening an output file on a disk that is already full
or is write-protected
14
Checking for a stream in fail state
First way:
Assuming myfile is declared as a filestream, either input or output,
myfile.fail() returns true if the stream has failed, false otherwise if (myfile.fail())
{ cout << “filestream failed” << endl;
return 1; // 1 to indicate something went wrong
}
Checking for a stream in fail state
Second way:
Assuming myfile is declared as a filestream, either input or output,
myfile (the name of the stream) is also considered a bool variable. It has the value true if the stream is good, false if failed if (!myfile)
{ cout << “filestream failed” << endl;
return 1; // 1 to indicate something went wrong
}
Processing a file's data
you must know how the data is arranged in the file, or you can't read it
different ways to process all the data in the file
one is put a count in the beginning that tells you how many pieces there are
the other is to put in some indicator - a sentinel - at the end of the data
Counter controlled reading
infile >> howmany;
ct = 0;
while (ct < howmany)
{ infile >> data;
// process data
ct ++;
}
// don't forget to put the count in the file! And
// make sure it's right!!
Sentinel controlled reading
more flexible - can add or take away data in file without having to change count
either use literal sentinel number OR use the file stream state itself as the event to
end the loop
Literal Sentinel value
infile >> data; // priming read, remember?
while (data != sentinel value)
{
// process data
infile >> data;
}
// don't forget to put the sentinel value in
// there!!
File stream sentinel event
infile >> data;
while (infile) // the name is true while
// the stream is ok
{ // process data
infile >> data;
}
// does not require ANY special value at the
// end of the file, handles ANY amount of data
why not use eof()?
some people like to use
while (! infile.eof())
which means to continue while the file stream hasn't set the eof flag to true yet
this flag is set ONLY when an attempt is made to read PAST the end of the file
other things can make the file stream fail that will NOT set the eof flag!
Suppose...
suppose the input file didn't open, so the stream is in a fail state from the start
"while (infile)" is going to skip the loop altogether and go on, whereas...
"while (!infile.eof())" is going to fall into the loop and never get out, because the stream is failed, and the input statements in the loop are never executed! so eof () cannot ever become true!
Suppose ... suppose there is data of the wrong type in the
file, like reading letters into an numeric variable this makes the stream fail but does NOT set
the eof() flag to true so the loop "while (!infile.eof())" will be an
infinite loop - again, input statements will be ignored because the data was bad, but eof() will never be true because we can't read and thus can't get past the end of file
Fail States - why do you get one?
input files can't open - input file doesn't exist data of alphabetic type read into numeric variable trying to read past end of file
output files can't open because the PATH does not exist can't write because there is no room on the
device
Errors in sentinel logic
// This is an ERROR!
while (infile)
{ infile >> data;
// process data
}
it will process the last piece of data TWICE!
Why?
The correct way to do sentinel logic
infile >> data; // priming read
while (infile) // could be !infile.fail()
{
// process your data as needed
infile >> data; // at BOTTOM of loop
}
top related