Class Bfs 12091159031978
Class Bfs 12091159031978
I/O Streams
UEE1302 (1102) F10 –File I/O
–Character I/O
Introduction to Computers
Tools for Stream I/O
and Programming (I)
–File names as input
–Formatting output , flag settings
Programming Lecture 09 Stream Hierarchies
File I/O & –Preview of inheritance
Data Manipulation Random Access to Files
What are streams? a transfer of information Standard streams are created, connected,
in the form of a sequence of bytes and disconnected automatically by OS.
–Special objects cin, cout, cerr, clog : behaves like a text file.
–Deliver program input and output
Input stream: flow into program
–Can come from keyboard or file
Output stream: flow out of program
–Can go to screen or file buffered
File: collection of data that is stored together Files have two names to our programs
under common name on storage media External filename
–C++ sources as text files on hard disks –Also called physical filename
Reading from file –Example: "input_file.txt"
–When program takes input –Sometimes considered real filename
Writing to file –Used only once in program (to open)
–When program sends output Stream name
Start at beginning of file to end –Also called logical filename
–Other methods available –Example: inFile in "ifstream inFile;"
–We’ll discuss this simple text file access –C++ program uses this name for all file
here activity
PRO_09 HUNG-PIN(CHARLES) WEN 7 PRO_09 HUNG-PIN(CHARLES) WEN 8
File Connection & File I/O Declaring Streams
Must first connect file to stream object Stream must be declared like any other
–For input: file ifstream object class variable:
–For output: file ofstream object ifstream inFile;
ofstream outFile;
Use ifstream and ofstream classes
#include <fstream> Must then connect to file:
inFile.open(“input_file.txt”);
using namespace std;
–Defined in library <fstream> –opening the file by member function open()
–can specify complete pathname
–Named in std namespace
–filename must be c-strings
Alternative form
#include <fstream> Can specify filename at declaration
using std::ifstream; ifstream inFile(“input_file.txt”);
using std::ofstream; ofstream outFile(“output_file.txt”);
PRO_09 HUNG-PIN(CHARLES) WEN 9 PRO_09 HUNG-PIN(CHARLES) WEN 10
Standard open operation begins with empty File opens could fail
file –If input file doesn’t exist
–Even if file exists contents lost –No write permissions to output file
Open for append: –Unexpected results
ofstream outFile; Place call to .fail() or .is_open() to check
outFile.open(“output.txt”,ios::app); stream operation success
–If file doesn’t exist creates it inStream.open(“stuff.txt”);
–If file exists appends to end if (inStream.fail())
{
–2nd argument is class ios defined constant cout << "File open failed.\n";
in <iostream> library, std namespace exit(1);
}
– .is_open() returns the opposite .fail()
PRO_09 HUNG-PIN(CHARLES) WEN 15 PRO_09 HUNG-PIN(CHARLES) WEN 16
Checking End-of-File w/ eof() Checking End-of-File w/ Read
Use loop to process file until end Second method: read operation returns bool
–two ways to test for the end of file value! a good way to read file
Use member function eof() (inStream >> next)
inStream.get(next); –expression returns true if read successful
while (!inStream.eof())
–return false if attempt to read beyond end
{
cout << next; of file
inStream.get(next); In action:
}
double next, sum = 0;
–Reads each character until file ends while (inStream >> next)
– eof() member function returns bool sum = sum + next;
–Member function get() comes soon! cout << “the sum is “ << sum << endl;
PRO_09 HUNG-PIN(CHARLES) WEN 17 PRO_09 HUNG-PIN(CHARLES) WEN 18
get(): obtain characters from file and save it to getline(): read characters into input stream
getline()
the input stream. 3 forms: buffer until either:
– istream& get(char& ch); most suggested –(num - 1) characters have been read,
– istream& get(char* buffer,streamsize num); –an EOF is encountered,
– istream& get(char* buffer,streamsize num,
–or, until the character delim (normally,
char delim);
newline, ‘\n’) is read. The delim character is
Example for Form 1: not put into buffer.
ifstream inFile(“input_file.dat”, ios::in);
Two forms:
char ichar;
– istream& getline(char* buffer,
while (inFile.get(ichar)) { streamsize num);
cout << ichar; – istream& getline(char* buffer,
} streamsize num, char delim);
PRO_09 HUNG-PIN(CHARLES) WEN 21 PRO_09 HUNG-PIN(CHARLES) WEN 22
Example 1 (for C-String variables): put(): put one character to the output stream
int MAX_LENGTH = 100; and save it to the file
char line[MAX_LENGTH]; Syntax: ostream& put(char ch);
while (inFile.getline(line, MAX_LENGTH)) { Example:
cout << “read line: ” << line << endl; ofstream outFile(“output_file.dat”);
} string article = “Today is Dec-30-2010.\n
Example 2 (for string variables): We still have two more lectures.\n
string line; Wish us a happy new year!\n”;
while (getline(inFile, line)) { for (int idx=0;idx < article.size();idx++)
cout << “read line: ” << line << endl; {
} outFile.put
put(article[idx]);
put
}
outFile.close();
PRO_09 HUNG-PIN(CHARLES) WEN 23 PRO_09 HUNG-PIN(CHARLES) WEN 24
putback(): Put Back One Character peek(): Read/Return Next Character
ignore(): read and throw away characters until Sequential file organization: characters in file
num characters have been read or until the are stored in sequential manner
character delim is read Random Access: any character in an opened
Syntax: istream& ignore(streamsize num=1, file can be read directly without having to
int delim=EOF);
read characters ahead of it
Example: File position marker: long integer that
char first, last;
represents an offset from the beginning of
cout << “Enter your first and last names:”;
each file
first = inFile.get();
inFile.ignore
ignore(256,‘
ignore ’);
–Keep track of where next character is to be
last = inFile.get(); read from or written to
cout <<"Your name is " << first << last; –Allow for random access of any individual
character
PRO_09 HUNG-PIN(CHARLES) WEN 27 PRO_09 HUNG-PIN(CHARLES) WEN 28
Random File Access (2/3) Random File Access (3/3)
Opens same as istream or ostream seekg() and seekp() can be used with three
fstream rwStream; modes: ios::beg, ios::cur and ios::end
rwStream.open(“stuff.txt”,ios::in|ios::out);
–Adds second argument (EX 1) infile.seekg(10, ios::beg)
–Open with read and write capability –File position marker moves to the 10th
Move about in file character from the beginning of the file
rwStream.seekp(1000); (EX 2) infile.seekg(-6, ios::cur)
–Positions put-pointer at 1000th byte –File position marker moves back 6
rwStream.seekg(1000);
characters from the current position
–Positions get-pointer at 1000th byte
rwStream.seekp(100*sizeof(myStrcut) – 1); (EX 3) outfile.seekp(0, ios::end)
–Position put-pointer at 100th record of objects –File position marker moves to the last
characters at the end of file
PRO_09 HUNG-PIN(CHARLES) WEN 31 PRO_09 HUNG-PIN(CHARLES) WEN 32
Parse Command Line Tools: File Names as Input
Using file’s external name in place of internal Attempting to detect end of file using
file stream object name when accessing file character variables for EOF marker
Opening file for output without first checking –Any variable used to accept EOF must be
that file with given name already exists declared as an integer variable
–Not checking for preexisting file ensures Using integer argument with the seekg() and
that file will be overwritten seekp() functions
Not understanding that end of a file is –Offset must be a long integer constant or
detected only after EOF sentinel has either variable
been read or passed over –Any other value passed to these functions
can result in unpredictable result
A data file is any collection of data stored in All file streams must be declared as objects of
an external storage medium under a common either the ifstream or ofstream classes
name Data files can be accessed randomly using
A data file is connected to file stream using the seekg(),seekp(),tellg(),and tellp()
methods
open() method in <fstream>
– g versions of these functions are used to
–connect file’s external name with internal alter and query file position marker for input
object name file streams
A file can be opened in input or output mode – p versions do the same for output file
–An opened output file stream either creates streams
a new data file or erases data in an existing Parse command line by
opened file int main(int argc, char *argv[])
PRO_09 HUNG-PIN(CHARLES) WEN 37 PRO_09 HUNG-PIN(CHARLES) WEN 38