File Input and Output in C++
-
Upload
solstice-rhoda -
Category
Documents
-
view
41 -
download
1
description
Transcript of File Input and Output in C++
![Page 1: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/1.jpg)
File Input and Output in C++
![Page 2: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/2.jpg)
Keyboard and Screen I/O
#include <iostream>
cin
(of type istream)
cout
(of type ostream)
KeyboardScreen
executingprogram
input data output data
2
![Page 3: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/3.jpg)
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)
![Page 4: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/4.jpg)
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
![Page 5: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/5.jpg)
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)
![Page 6: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/6.jpg)
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
![Page 7: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/7.jpg)
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
![Page 8: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/8.jpg)
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
![Page 9: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/9.jpg)
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
![Page 10: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/10.jpg)
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
![Page 11: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/11.jpg)
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
![Page 12: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/12.jpg)
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 . . .;
![Page 13: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/13.jpg)
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.
![Page 14: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/14.jpg)
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
![Page 15: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/15.jpg)
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
}
![Page 16: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/16.jpg)
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
}
![Page 17: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/17.jpg)
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
![Page 18: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/18.jpg)
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!!
![Page 19: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/19.jpg)
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
![Page 20: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/20.jpg)
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!!
![Page 21: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/21.jpg)
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
![Page 22: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/22.jpg)
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!
![Page 23: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/23.jpg)
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!
![Page 24: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/24.jpg)
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
![Page 25: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/25.jpg)
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
![Page 26: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/26.jpg)
Errors in sentinel logic
// This is an ERROR!
while (infile)
{ infile >> data;
// process data
}
it will process the last piece of data TWICE!
Why?
![Page 27: File Input and Output in C++](https://reader036.fdocuments.in/reader036/viewer/2022062304/56813739550346895d9eca1c/html5/thumbnails/27.jpg)
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
}