0% found this document useful (0 votes)
39 views

Class Bfs 12091159031978

The document discusses file input/output (I/O) streams in C++. It introduces file streams like ifstream and ofstream that allow reading from and writing to files. It covers opening, reading from, writing to, and closing files. It also discusses checking for errors when opening files and detecting the end of a file, such as using eof() or checking the return value of read operations.

Uploaded by

TarikuDabala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Class Bfs 12091159031978

The document discusses file input/output (I/O) streams in C++. It introduces file streams like ifstream and ofstream that allow reading from and writing to files. It covers opening, reading from, writing to, and closing files. It also discusses checking for errors when opening files and detecting the end of a file, such as using eof() or checking the return value of read operations.

Uploaded by

TarikuDabala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Computational Intelligence on Automation Lab @ NCTU Learning Objectives

 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

PRO_09 HUNG-PIN(CHARLES) WEN 2

Introduction to Streams Illustration of <iostream>

 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

 Seen streams already!!  <iostream> un-buffered


– cin: input stream connected to keyboard
– cout: output stream connected to screen
PRO_09 HUNG-PIN(CHARLES) WEN 3 PRO_09 HUNG-PIN(CHARLES) WEN 4
Streams Like cin & cout Illustration of File Streams

 Given program defines stream inStream  input stream


that comes from some file:  output stream
 input/output stream
int number;
inStream >> number;
–Reads value from stream, assigned to
variable number
 Program defines stream outStream that goes to
some file
outStream << “the number is “ << number;
–Writes value to stream, which goes to file
 Program defines stream to come from and go
to some file concurrently.
PRO_09 HUNG-PIN(CHARLES) WEN 5 PRO_09 HUNG-PIN(CHARLES) WEN 6

Files File Names

 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

File Streams Usage Open File Stream w/ Flags

 Once declared  use normally!


int oneNumber, anotherNumber; flag Explanation
inFile >> oneNumber >> anotherNumber;
ios::in input state; default for input file
 Output stream similar: ios::out output state; default for output file
ofstream outFile;
outFile.open
.open(“output_file.txt”);
.open ios::app Append output state.
outFile << “oneNumber = “ ios::ate Position file marker at the end of file
<< oneNumber ios::trunc Delete all data from an existing file when it
<< “anotherNumber = “ is opened. Default for output file.
<< anotherNumber;
ios::binary Binary file; default is text file.
 Send items to output file

PRO_09 HUNG-PIN(CHARLES) WEN 11 PRO_09 HUNG-PIN(CHARLES) WEN 12


Closing Files File Flush

 Files should be closed  Output often buffered


–When program completed getting input or –Temporarily stored before written to file
sending output –Written in groups
–Disconnects stream from file  Occasionally might need to force writing:
 Example: outStream.flush();
inStream.close(); –Member function flush, for all output
outStream.close(); streams
–no arguments –All buffered output is physically written
 Files automatically close when program ends  Closing file automatically calls flush()
–Good to close opened files explicitly

PRO_09 HUNG-PIN(CHARLES) WEN 13 PRO_09 HUNG-PIN(CHARLES) WEN 14

Appending to a File Checking File Open Success

 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

Checking File I/O Status Character I/O with Files

 All cin and cout character I/O same for files!


prototype description
 Common character I/O functions
return true if the file has not been opened
fail() – get(), getline(): obtain characters from
successfully; otherwise, return false
input file
return true if a read has been attempted past – put(): put one character to output streams
eof() the end-of-file; otherwise, return false – putback(): put back the character just read
return true if the file is available for program
to input streams
good() use; otherwise, return false – peek(): return the next character from the
stream without removing it
return true if a fatal error with the current – ignore(): skips over a designated number
bad() stream has occurred; otherwise, false. not of characters
normally occur.
PRO_09 HUNG-PIN(CHARLES) WEN 19 PRO_09 HUNG-PIN(CHARLES) WEN 20
get(): Read Characters from File getline(): Read a Line from File

 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

Examples of getline() put(): Put One Character to File

 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

putback(): return the previously-read


 putback()  peek(): return the next character in the
character ch to the input stream stream or EOF if the end of file is read
 Syntax: istream& putback( char ch ); –not remove the character from the stream
 Example: // get a number or a word?  Example: // get a number or a word?
ifstream inFile(“sample.dat”);
ifstream inFile(“sample.dat”);
int n = 0;
int n = 0;
char str[256];
char str[256];
char c = inFile.get();
if ( (c >= ‘0’) && (c <= ‘9’) ) { char c = inFile.peek
peek();
peek
inFile.putback
putback(c);
putback if ( (c >= ‘0’) && (c <= ‘9’) ) {
inFile >> n; // this case is a number inFile >> n; // this case is a number
} else { } else {
inFile.putback
putback(c);
putback cin >> str; //this case is a word
cin >> str; //this case is a word }
PRO_09 } HUNG-PIN(CHARLES) WEN 25 PRO_09 HUNG-PIN(CHARLES) WEN 26

ignore(): Skip Characters Random File Access (1/3)

 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)

 Finding record 101 using sequential access: Name description


–One file = a sequential stream of n For input files, move to the offset position
seekg(offset,mode)
as indicated by the mode
characters
For output files, move to the offset
seekp(offset,mode)
position as indicated by the mode
0 1 2 … 100 101 102 … For input files, return the current value of
tellg(void)
the file position marker
ios:beg ios:cur ios:end For output files, return the current value
tellp(void)
of the file position marker
 Finding record 101 using random access:
 Types of modes:
– ios::beg: the beginning of the file
0 1 2 … 100 101 102 …
– ios::cur: current position of the file
ios:beg ios:cur ios:end – ios::end: the end of the file
PRO_09 HUNG-PIN(CHARLES) WEN 29 PRO_09 HUNG-PIN(CHARLES) WEN 30

Random Access Tools (1/2) Random Access Tools (2/2)

 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

 Obtain parameters from command line by  Stream open operation


int main(int argc, char *argv[]) –Argument to open() is c-string type
– argc: total count of the parameters –Can be literal (used so far) or variable
including the program name string fileName;
– argv: indexed array of c-strings ifstream inFile;
 Example: cout << “Enter file name: “;
cin >> fileName;
>./prog dog cat tiger
inFile.open(fileName.c_str());
– argc is 4
–Provides more flexibility
– argv[0] is “prog”
 Open file from command line argument
– argv[1] is “dog”
– argv[2] is “cat” –Ex: inFile.open(argv[2]);
– argv[3] is “tiger”
PRO_09 HUNG-PIN(CHARLES) WEN 33 PRO_09 HUNG-PIN(CHARLES) WEN 34

Common Programming Errors (1/2) Common Programming Errors (2/2)

 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

PRO_09 HUNG-PIN(CHARLES) WEN 35 PRO_09 HUNG-PIN(CHARLES) WEN 36


Summary (1/2) Summary (2/2)

 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

You might also like