SlideShare a Scribd company logo
1
Stream Classes
 A stream is a general name given to a flow of data.
 In C++ a stream is represented by an object of a particular class. So far we’ve
used the cin and cout stream objects.
 Different streams are used to represent different kinds of data flow. For
example, the ifstream class represents data flow from input disk files.
Advantages of Streams
 One reason is simplicity. Another reason is that you can overload existing
operators and functions, such as the insertion (<<) and extraction (>>)
operators, to work with classes that you create.
 You should know about C++ streams because they are the best way to write
data to files and to format data in memory for later use in text input/output
windows and other GUI elements.
[2]
The Stream Class Hierarchy
[3]
The Stream Class Hierarchy
[4]
The Stream Class Hierarchy
 ios class is the base class for the hierarchy. It contains many constants and
member functions common to input and output operations, such as the
showpoint and fixed formatting flags
 The ios class also contains a pointer to the streambuf class, which contains the
actual memory buffer into which data is read or written.
 The istream and ostream classes are derived from ios and are dedicated to
input and output, respectively.
 The istream class contains such functions as get(), getline(), read(), and the
 overloaded extraction (>>) operators, while ostream contains put() and
write(), and the overloaded insertion (<<) operators.
 The iostream class is derived from both istream and ostream by multiple
inheritance. Classes derived from it can be used with devices, such as disk
files, that may be opened for both input and output at the same time. [5]
The Stream Class Hierarchy
 Three classes istream_withassign, ostream_withassign, and
iostream_withassign are inherited from istream, ostream, and iostream,
respectively. They add assignment operators to these classes.
 The cout object, is a predefined object of the ostream_withassign class
 Similarly, the cin is an object of the istream_withassign class
 The classes used for input and output to the video display and keyboard are
declared in the header file IOSTREAM.
 The classes used specifically for disk file I/O are declared in the file FSTREAM.
[6]
Disk File I/O with Streams
 Most programs need to save data to disk files and read it back in. Working
with disk files requires another set of classes:
 ifstream for input
 fstream for both input and output
 and ofstream for output.
 Objects of these classes can be associated with disk files, and we can use their
member functions to read and write to the files.
 These three classes are declared in the FSTREAM file.
[7]
Formatted File I/O
 In formatted I/O, numbers are stored on disk as a series of characters. Thus
6.02, rather than being stored as a 4-byte type float or an 8-byte type double,
is stored as the characters ‘6’, ‘.’, ‘0’, and ‘2’.
 This can be inefficient for numbers with many digits, but it’s appropriate in
many situations and easy to implement.
[8]
// writes formatted output to a file
// using << operator
#include <fstream> // for file I/O
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
char ch = 'x';
int j = 77;
double d = 6.02;
// strings without embedded spaces
string str1 = "Rashid";
string str2 = "Farid";
// create ofstream object
ofstream outfile("data.txt");
9
Example 1: Writing Data to a File
outfile << ch // insert (write) data
<< j
<< ' ' // needs space between numbers
<< d
<< str1
<< ' ' //needs spaces between strings
<< str2;
cout << "File writtenn";
system("pause");
return 0;
}
1 2
[9]
Example 1: Writing Data to a File
 If the file doesn’t exist, it is created. If it does exist, it is truncated and the new data
replaces the old.
 The outfile object acts much as cout did in previous programs, so we can use the insertion
operator (<<) to output variables of any basic type to the file.
 This works because the insertion operator is appropriately overloaded in ostream, from
which ofstream is derived.
 When the program terminates, the outfile object goes out of scope. This calls its destructor,
which closes the file, so we don’t need to close the file explicitly
 There are several potential formatting glitches. First, you must separate numbers (such as
77 and 6.02) with nonnumeric characters.
 As numbers are stored as a sequence of characters, this is the only way the extraction
operator will know, when the data is read back from the file, where one number stops and
the next one begins.
[10]
Example 1: Writing Data to a File
 Second, strings must be separated with whitespace for the same reason. This
implies that strings cannot contain imbedded blanks.
 In this example we use the space character (‘ ‘) for both kinds of delimiters.
Characters need no delimiters, since they have a fixed length.
 You can verify that program has indeed written the data by examining the
DATA.TXT file with the Windows NOTEPAD accessory or the DOS command
TYPE.
[11]
// reads formatted output from a file
// using >> operator
#include <fstream> // for file I/O
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
char ch;
int j;
double d;
string str1, str2;
// create ifstream object
ifstream infile("data.txt");
//extract (read) data from it
infile >> ch
>> j
>> d
>> str1
>> str2;
12
Example 2: Reading Data from a File
cout << ch << endl // display the data
<< j << endl
<< d << endl
<< str1 << endl
<< str2 << endl;
system("pause");
return 0;
}
1 2
[12]
 If you’ve ever used MS-DOS, you are
probably familiar with command-line
arguments, used when invoking a
program. They are typically used to
pass the name of a data file to an
application. For example, you can
invoke a word processor application
and the document it will work on at the
same time:
 C>wordproc afile.doc
 Here afile.doc is a command-line
argument. How can we get a C++
program to read the command-line
arguments? Here’s an example
13
Example 3: Command-Line Arguments
#include <iostream>
using namespace std;
int main(int argc, char* argv[] ) {
// number of arguments
cout << "argc = " << argc << endl;
// display arguments
for(int j=0; j<argc; j++)
cout << "Argument " << j << " = "
<< argv[j] << endl;
return 0;
}
[13]
Command-Line Arguments
 And here’s a sample interaction with the program:
 To read command-line arguments, the main() function (don’t forget it’s a function!) must
itself be given two arguments. The first, argc (for argument count), represents the total
number of command-line arguments. The first command-line argument is always the
pathname of the current program. The remaining command-line arguments are those
typed by the user; they are delimited by the space character. In the preceding example they
are uno, dos, and tres.
[14]
#include <fstream> // for file
#include <iostream>
#include <process.h> //for exit()
using namespace std;
int main(int argc, char* argv[] ) {
if( argc != 2 ) {
cerr << "Format: oop filename"
<< endl;
exit(-1);
}
char ch; //character to read
ifstream infile; // to read a file
infile.open( argv[1] );// open file
15
Example 4: Command-Line Arguments
if( !infile ) { // check for errors
cerr << "nCan't open "
<< argv[1];
exit(-1);
}
while( infile.get(ch) != 0 ) //read a character
cout << ch; //display the character
return 0;
}
1 2
[15]
Strings with Embedded Blanks
 The technique of our last examples won’t work with char* strings containing
embedded blanks.
 To handle such strings, you need to write a specific delimiter character after
each string, and use the getline()function, rather than the extraction
operator, to read them in.
 Our next program, outputs some strings with blanks embedded in them.
[16]
// file output with strings
#include <fstream> // for file I/O
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
// create file for output
ofstream outfile("data.txt");
//send text to file
outfile << "I fear thee, ancient!n";
outfile << "I fear thy skinny handn";
outfile << "And thou art long brown,n";
system("pause");
return 0;
}
17
Example 5, 6: Writing and Reading String in a File
// file input with strings
#include <fstream> // for file I/O
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int MAX = 80; // size of buffer
char buffer[MAX]; // character buffer
// create file for input
ifstream infile("data.txt");
while (!infile.eof()){ // until end-of-file
// read a line of text
infile.getline(buffer, MAX);
// display it
cout << buffer << endl;
}
system("pause");
return 0;
}
1 2
[17]
Writing and Reading String in a File
 This program requires all the text lines to terminate with the ‘n’ character, and if you
encounter a file in which this is not the case, the program will hang.
 The program continues to read one string at a time until it encounters an end-of-file (EOF)
condition. The EOF is a signal sent to the program from the operating system when there is
no more data to read.
 However, checking specifically for an eofbit means that we won’t detect the other error
flags, such as the failbit and badbit, which may also occur, although more rarely. To do this,
we can change our loop condition:
while (infile.good()){ // until any error encountered
 You can also test the stream directly. If everything is going well, the object infile returns a
nonzero value which is a pointer. Thus we can rewrite our while loop again:
while (infile){ // until any error encountered
[18]
// file output with characters
#include <fstream> // for file I/O
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
string str = "Time is a great teacher,"
" but unfortunately it kills all its"
" pupils. Berlioz";
// create file for output
ofstream outfile("data.txt");
for (unsigned int j = 0;
j < str.size(); j++)
// write it to file
outfile.put(str[j]);
cout << "File writtenn";
system("pause");
return 0;
}
19
Example 7, 8: Character I/O
// file input with characters
#include <fstream> // for file I/O
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
char ch; // character to read
// create file for output
ifstream infile("data.txt");
// read until the EOF is reached
// or an error occurs
while (infile){
infile.get(ch);
// read a character
cout << ch; // display it
}
cout << endl;
system("pause");
return 0;
}
1 2
[19]
Binary I/O
 You can write a few numbers to disk using formatted I/O, but if you’re storing
a large amount of numerical data it’s more efficient to use binary I/O, in which
numbers are stored as they are in the computer’s RAM memory, rather than
as strings of characters.
 In binary I/O an int is stored in 4 bytes, whereas its text version might be
“12345”, requiring 5 bytes. Similarly, a float is always stored in 4 bytes, while
its formatted version might be “6.02314e13”, requiring 10 bytes.
 example shows how an array of integers is written to disk and then read back
into memory, using binary format.
 We use write(), a member of ofstream; and read(), a member of ifstream.
 These functions think about data in terms of bytes (type char). They don’t care
how the data is formatted, they simply transfer a buffer full of bytes from and
to a disk file. [20]
// binary input and output with integers
#include <fstream> //for file streams
#include <iostream>
#include <stdlib.h>
using namespace std;
const int MAX = 100; //size of buffer
int buff[MAX]; //buffer for integers
int main() {
int i;
for (i = 0; i < MAX; i++) // fill buffer with data { 0, 1, 2, ... ,99}
buff[i] = i;
ofstream os("numbers.txt", ios::binary); // create output stream
os.write((char*)buff, MAX * sizeof(int)); // write to it
os.close(); // must close it
for (i =0; i < MAX; i++) // erase buffer
buff[i] = 0;
ifstream is("numbers.txt", ios::binary); // create input stream
is.read((char*)buff, MAX * sizeof(int)); // read from it
Example 9: Binary I/O with integers (1/2)
[21]
for (i = 0; i < MAX; i++) // check data
if (buff[i] != i){
cerr << i<< " Data is incorrectn";
return 1;
}
cout << "Data is correctn";
system("pause");
return 0;
}
Example 9: Binary I/O with integers (2/2)
[22]
Object I/O
 Since C++ is an object-oriented language, it’s reasonable to wonder how
objects can be written to and read from disk.
 The next examples show the process
 When writing an object, we generally want to use binary mode. This writes
the same bit configuration to disk that was stored in memory, and ensures
that numerical data contained in objects is handled properly.
 Here’s the listing for OPERS, which asks the user for information about an
object of class person, and then writes this object to the disk file PERSON.DAT
[23]
#include <fstream> // for file streams
#include <iostream>
using namespace std;
class person { // class of persons
protected:
char name[80]; // person’s name
short age; // person’s age
public:
void getData() { //get person’s data
cout << "Enter name : "; cin.get(name,80);
cout << "Enter age : " ; cin >> age;
}
};
int main() {
person pr1; // create a person
pr1.getData(); // get data for person 1
ofstream outfile("PERSON.DAT", ios::binary); // create ofstream object
outfile.write((char*) &pr1, sizeof(pr1)); // write to it
return 0;
}
Example 10: Writing Object to a File
[24]
// saves person object to disk
#include <fstream> // for file streams
#include <iostream>
using namespace std;
class person {
protected:
char name[80]; // person’s name
short age; // person’s age
public:
void showData() { // display person’s data
cout << "Name: " << name << endl;
cout << "Age : " << age << endl;
}
};
int main() {
person pr1; // create a person
ifstream infile("PERSON.DAT", ios::binary);
infile.read((char*) &pr1, sizeof(pr1)); // read from file
pr1.showData(); return 0;
}
Example 10: Reading Object from a File
[25]
istream Functions
[26]
Function Purpose
>> Formatted extraction for all basic (and overloaded) types.
get(ch) Extract one character into ch.
getline(str, MAX) Extract one line into array str, until MAX characters or the ‘n’ character
getline(str, MAX, DELIM) Extract characters into array str, until MAX characters or the DELIM character.
putback(ch) Insert last character read back into input stream.
ignore(MAX, ‘n’) Extract and discard up to MAX characters until (and including) the specified delimiter ‘n’.
ch = stream.peek( ) Read one character, leave it in stream.
read(str, MAX) For files, extract up to MAX characters into str, until EOF.
seekg(n) Set distance (n bytes) of file pointer from start of file. e.g.
infile.seekg(0, ios::end); // go to 0 bytes from end
seekg(pos, seek_dir) Set distance (in bytes) of file pointer from specified place in file. seek_dir can be ios::beg,
ios::cur, ios::end.
tellg( ) Return position (in bytes) of file pointer from start of file. e.g. int endposition = infile.tellg();
ostream Functions
[27]
Function Purpose
<< Formatted insertion for all basic (and overloaded) types.
put(ch) Insert one character ch into stream.
flush() Flush buffer contents and Insert newline.
write(str, SIZE) Insert SIZE characters from array str into file.
seekp(n) Set distance in n bytes of file pointer from start of file.
seekp(pos, seek_dir) Set distance (in bytes) of file pointer from specified place in file. seek_dir can be ios::beg,
ios::cur, ios::end.
tellgp( ) Return position (in bytes) of file pointer from start of file. e.g. int endposition = outfile.tellg();
#include <fstream> // for file streams
#include <iostream>
using namespace std;
class Book
{
protected:
char title[80];
char auther[80];
double price;
public:
void Add_Record();
void Read_All();
void Search();
void Delete();
};
Example 11: Books Management System (1/8)
[28]
void Book::Add_Record() {
cout << "Enter title : ";
// eat chars, including newline
cin.ignore(80, 'n');
cin.getline(title, 80);
cout << "Enter Auther : ";
cin.getline(auther, 80);
cout << "Enter Price : ";
cin >> price;
cout << "Title = " << title << endl;
cout << "Auther = " << auther << endl;
cout << "Price = " << price << endl;
ofstream outfile;
outfile.open("books.txt", std::ios_base::app);
outfile << title << "" << auther << "" << price << endl;
system("pause");
}
Example 11: Books Management System (2/8)
[29]
void Book::Read_All() {
system("CLS");
const int MAX = 240; int S_No = 0;
char buffer[MAX]; // character buffer
ifstream infile("books.txt");
while (infile) {
infile.getline(buffer, MAX);
if (strlen(buffer) > 0) {
const char* delim = "";
char* next_token;
char* title = strtok_s(buffer, delim, &next_token);
char* auther = strtok_s(NULL, delim, &next_token);
char* prc = strtok_s(NULL, delim, &next_token);
cout << "#" << ++S_No << endl;
cout << " Title = " << title << endl;
cout << " Auther = " << auther << endl;
cout << " Price = " << prc << endl;
}
}
}
Example 11: Books Management System (3/8)
[30]
void Book::Search() {
int S_No = 0;
cout << "Enter title to Search: ";
// eat chars, including newline
cin.ignore(80, 'n');
cin.getline(this->title, 80);
system("CLS");
const int MAX = 240; // size of buffer
char buffer[MAX]; // character buffer
ifstream infile("books.txt");
while (infile) {
infile.getline(buffer, MAX);
if (strlen(buffer) > 0) {
const char* delim = "";
char* next_token;
char* title = strtok_s(buffer, delim, &next_token);
char* auther = strtok_s(NULL, delim, &next_token);
char* prc = strtok_s(NULL, delim, &next_token);
char* output = strstr(title, this->title);
Example 11: Books Management System (4/8)
[31]
S_No++;
if (output) {
cout << "#" << S_No << endl;
cout << "Title = " << title << endl;
cout << "Auther = " << auther << endl;
cout << "Price = " << prc << endl;
cout << "_________________________________" << endl;
}
}
}
}
void Book::Delete() {
system("CLS");
const int MAX = 240; // size of buffer
int R_No = 0, S_No = 0;
cout << "Please Enter Record Number: ";
cin >> R_No;
char buffer[MAX]; // character buffer
ifstream infile("books.txt");
ofstream outfile("temp.txt");
Example 11: Books Management System (5/8)
[32]
while (infile) {
infile.getline(buffer, MAX);
if (strlen(buffer) > 0) {
const char* delim = "";
char* next_token;
char* title = strtok_s(buffer, delim, &next_token);
char* auther = strtok_s(NULL, delim, &next_token);
char* prc = strtok_s(NULL, delim, &next_token);
S_No++;
if (S_No == R_No) {
char choice;
cout << "#" << S_No << endl;
cout << " Title = " << title << endl;
cout << " Auther = " << auther << endl;
cout << " Price = " << prc << endl;
cout << "Do you want to Delete this Record [y/n]?: ";
cin >> choice;
if (choice == 'y')
continue;
Example 11: Books Management System (6/8)
[33]
else
outfile << title << "" << auther << "" << prc << endl;
}
else
outfile << title << "" << auther << "" << prc << endl;
}
}
infile.close();
outfile.close();
remove("books.txt");
rename("temp.txt", "books.txt");
}
int main() {
Book b;
while (1) {
char choice;
cout << "[Operations]" << endl;
cout << "A - Add" << endl;
cout << "D - Delete" << endl;
Example 11: Books Management System (7/8)
[34]
cout << "R - Read All" << endl;
cout << "S - Search Title" << endl;
cout << "Q - Quit " << endl;
cin >> choice;
switch (choice) {
case 'A':
case 'a': b.Add_Record(); break;
case 'D':
case 'd': b.Delete(); break;
case 'R':
case 'r': b.Read_All(); break;
case 'S':
case 's': b.Search(); break;
case 'Q':
case 'q': exit(0);
default: cout << "Wrong Choice" << endl;
}
}
return 0;
}
Example 11: Books Management System (8/8)
[35]

More Related Content

Similar to Object Oriented Programming Using C++: Ch12 Streams and Files.pptx

17 files and streams
17 files and streams17 files and streams
17 files and streams
Docent Education
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with files
ramya marichamy
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
kirupasuchi1996
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
Daniel Nyagechi
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
Dr .Ahmed Tawwab
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
ANUSUYA S
 
File Handling in C++
File Handling in C++File Handling in C++
file.ppt
file.pptfile.ppt
file.ppt
DeveshDewangan5
 
Ds lec 14 filing in c++
Ds lec 14 filing in c++Ds lec 14 filing in c++
Ds lec 14 filing in c++
Taimoor Suleman
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
arnold 7490
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
Hemantha Kulathilake
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
faithxdunce63732
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
WondimuBantihun1
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptx
radhushri
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with example
Sunil Patel
 

Similar to Object Oriented Programming Using C++: Ch12 Streams and Files.pptx (20)

17 files and streams
17 files and streams17 files and streams
17 files and streams
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with files
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
file.ppt
file.pptfile.ppt
file.ppt
 
Ds lec 14 filing in c++
Ds lec 14 filing in c++Ds lec 14 filing in c++
Ds lec 14 filing in c++
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Files in c++
Files in c++Files in c++
Files in c++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptx
 
working with files
working with filesworking with files
working with files
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with example
 

More from RashidFaridChishti

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
RashidFaridChishti
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
RashidFaridChishti
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 

More from RashidFaridChishti (20)

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 

Recently uploaded

Adv. Digital Signal Processing LAB MANUAL.pdf
Adv. Digital Signal Processing LAB MANUAL.pdfAdv. Digital Signal Processing LAB MANUAL.pdf
Adv. Digital Signal Processing LAB MANUAL.pdf
T.D. Shashikala
 
Online toll plaza booking system project report.doc.pdf
Online toll plaza booking system project report.doc.pdfOnline toll plaza booking system project report.doc.pdf
Online toll plaza booking system project report.doc.pdf
Kamal Acharya
 
Quadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and ControlQuadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and Control
Blesson Easo Varghese
 
readers writers Problem in operating system
readers writers Problem in operating systemreaders writers Problem in operating system
readers writers Problem in operating system
VADAPALLYPRAVEENKUMA1
 
RECENT DEVELOPMENTS IN RING SPINNING.pptx
RECENT DEVELOPMENTS IN RING SPINNING.pptxRECENT DEVELOPMENTS IN RING SPINNING.pptx
RECENT DEVELOPMENTS IN RING SPINNING.pptx
peacesoul123
 
Ludo system project report management .pdf
Ludo  system project report management .pdfLudo  system project report management .pdf
Ludo system project report management .pdf
Kamal Acharya
 
API-1150WB-Cooling Towers.pdf with details
API-1150WB-Cooling Towers.pdf with detailsAPI-1150WB-Cooling Towers.pdf with details
API-1150WB-Cooling Towers.pdf with details
MuhammadUsmanAsghar4
 
The world of Technology Management MEM 814.pptx
The world of Technology Management MEM 814.pptxThe world of Technology Management MEM 814.pptx
The world of Technology Management MEM 814.pptx
engrasjadshahzad
 
PPT_grt.pptx engineering criteria grt for accrediation
PPT_grt.pptx engineering criteria  grt for accrediationPPT_grt.pptx engineering criteria  grt for accrediation
PPT_grt.pptx engineering criteria grt for accrediation
SHALINIRAJAN20
 
Buy a fake University of Washington diploma
Buy a fake University of Washington diplomaBuy a fake University of Washington diploma
Buy a fake University of Washington diploma
College diploma
 
How to Formulate A Good Research Question
How to Formulate A  Good Research QuestionHow to Formulate A  Good Research Question
How to Formulate A Good Research Question
rkpv2002
 
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
amzhoxvzidbke
 
charting the development of the autonomous train
charting the development of the autonomous traincharting the development of the autonomous train
charting the development of the autonomous train
huseindihon
 
ARITMETICO.pdf xxxxxxxxxxxxxxxxxxxxxxxx
ARITMETICO.pdf  xxxxxxxxxxxxxxxxxxxxxxxxARITMETICO.pdf  xxxxxxxxxxxxxxxxxxxxxxxx
ARITMETICO.pdf xxxxxxxxxxxxxxxxxxxxxxxx
alemaro1123
 
# Smart Parking Management System.pptx using IOT
# Smart Parking Management System.pptx using IOT# Smart Parking Management System.pptx using IOT
# Smart Parking Management System.pptx using IOT
Yesh20
 
Evento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recapEvento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recap
Rafael Santos
 
OSHA LOTO training, LOTO, lock out tag out
OSHA LOTO training, LOTO, lock out tag outOSHA LOTO training, LOTO, lock out tag out
OSHA LOTO training, LOTO, lock out tag out
Ateeb19
 
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdfRed Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
mdfkobir
 
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATAFINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
kevig
 
Presentation slide on DESIGN AND FABRICATION OF MOBILE CONTROLLED DRAINAGE.pptx
Presentation slide on DESIGN AND FABRICATION OF MOBILE CONTROLLED DRAINAGE.pptxPresentation slide on DESIGN AND FABRICATION OF MOBILE CONTROLLED DRAINAGE.pptx
Presentation slide on DESIGN AND FABRICATION OF MOBILE CONTROLLED DRAINAGE.pptx
Er. Kushal Ghimire
 

Recently uploaded (20)

Adv. Digital Signal Processing LAB MANUAL.pdf
Adv. Digital Signal Processing LAB MANUAL.pdfAdv. Digital Signal Processing LAB MANUAL.pdf
Adv. Digital Signal Processing LAB MANUAL.pdf
 
Online toll plaza booking system project report.doc.pdf
Online toll plaza booking system project report.doc.pdfOnline toll plaza booking system project report.doc.pdf
Online toll plaza booking system project report.doc.pdf
 
Quadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and ControlQuadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and Control
 
readers writers Problem in operating system
readers writers Problem in operating systemreaders writers Problem in operating system
readers writers Problem in operating system
 
RECENT DEVELOPMENTS IN RING SPINNING.pptx
RECENT DEVELOPMENTS IN RING SPINNING.pptxRECENT DEVELOPMENTS IN RING SPINNING.pptx
RECENT DEVELOPMENTS IN RING SPINNING.pptx
 
Ludo system project report management .pdf
Ludo  system project report management .pdfLudo  system project report management .pdf
Ludo system project report management .pdf
 
API-1150WB-Cooling Towers.pdf with details
API-1150WB-Cooling Towers.pdf with detailsAPI-1150WB-Cooling Towers.pdf with details
API-1150WB-Cooling Towers.pdf with details
 
The world of Technology Management MEM 814.pptx
The world of Technology Management MEM 814.pptxThe world of Technology Management MEM 814.pptx
The world of Technology Management MEM 814.pptx
 
PPT_grt.pptx engineering criteria grt for accrediation
PPT_grt.pptx engineering criteria  grt for accrediationPPT_grt.pptx engineering criteria  grt for accrediation
PPT_grt.pptx engineering criteria grt for accrediation
 
Buy a fake University of Washington diploma
Buy a fake University of Washington diplomaBuy a fake University of Washington diploma
Buy a fake University of Washington diploma
 
How to Formulate A Good Research Question
How to Formulate A  Good Research QuestionHow to Formulate A  Good Research Question
How to Formulate A Good Research Question
 
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
杨洋李一桐做爱视频流出【网芷:ht28.co】国产国产午夜精华>>>[网趾:ht28.co】]<<<
 
charting the development of the autonomous train
charting the development of the autonomous traincharting the development of the autonomous train
charting the development of the autonomous train
 
ARITMETICO.pdf xxxxxxxxxxxxxxxxxxxxxxxx
ARITMETICO.pdf  xxxxxxxxxxxxxxxxxxxxxxxxARITMETICO.pdf  xxxxxxxxxxxxxxxxxxxxxxxx
ARITMETICO.pdf xxxxxxxxxxxxxxxxxxxxxxxx
 
# Smart Parking Management System.pptx using IOT
# Smart Parking Management System.pptx using IOT# Smart Parking Management System.pptx using IOT
# Smart Parking Management System.pptx using IOT
 
Evento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recapEvento anual Splunk .conf24 Highlights recap
Evento anual Splunk .conf24 Highlights recap
 
OSHA LOTO training, LOTO, lock out tag out
OSHA LOTO training, LOTO, lock out tag outOSHA LOTO training, LOTO, lock out tag out
OSHA LOTO training, LOTO, lock out tag out
 
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdfRed Hat Enterprise Linux Administration 9.0 RH124 pdf
Red Hat Enterprise Linux Administration 9.0 RH124 pdf
 
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATAFINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
FINE-TUNING OF SMALL/MEDIUM LLMS FOR BUSINESS QA ON STRUCTURED DATA
 
Presentation slide on DESIGN AND FABRICATION OF MOBILE CONTROLLED DRAINAGE.pptx
Presentation slide on DESIGN AND FABRICATION OF MOBILE CONTROLLED DRAINAGE.pptxPresentation slide on DESIGN AND FABRICATION OF MOBILE CONTROLLED DRAINAGE.pptx
Presentation slide on DESIGN AND FABRICATION OF MOBILE CONTROLLED DRAINAGE.pptx
 

Object Oriented Programming Using C++: Ch12 Streams and Files.pptx

  • 1. 1
  • 2. Stream Classes  A stream is a general name given to a flow of data.  In C++ a stream is represented by an object of a particular class. So far we’ve used the cin and cout stream objects.  Different streams are used to represent different kinds of data flow. For example, the ifstream class represents data flow from input disk files. Advantages of Streams  One reason is simplicity. Another reason is that you can overload existing operators and functions, such as the insertion (<<) and extraction (>>) operators, to work with classes that you create.  You should know about C++ streams because they are the best way to write data to files and to format data in memory for later use in text input/output windows and other GUI elements. [2]
  • 3. The Stream Class Hierarchy [3]
  • 4. The Stream Class Hierarchy [4]
  • 5. The Stream Class Hierarchy  ios class is the base class for the hierarchy. It contains many constants and member functions common to input and output operations, such as the showpoint and fixed formatting flags  The ios class also contains a pointer to the streambuf class, which contains the actual memory buffer into which data is read or written.  The istream and ostream classes are derived from ios and are dedicated to input and output, respectively.  The istream class contains such functions as get(), getline(), read(), and the  overloaded extraction (>>) operators, while ostream contains put() and write(), and the overloaded insertion (<<) operators.  The iostream class is derived from both istream and ostream by multiple inheritance. Classes derived from it can be used with devices, such as disk files, that may be opened for both input and output at the same time. [5]
  • 6. The Stream Class Hierarchy  Three classes istream_withassign, ostream_withassign, and iostream_withassign are inherited from istream, ostream, and iostream, respectively. They add assignment operators to these classes.  The cout object, is a predefined object of the ostream_withassign class  Similarly, the cin is an object of the istream_withassign class  The classes used for input and output to the video display and keyboard are declared in the header file IOSTREAM.  The classes used specifically for disk file I/O are declared in the file FSTREAM. [6]
  • 7. Disk File I/O with Streams  Most programs need to save data to disk files and read it back in. Working with disk files requires another set of classes:  ifstream for input  fstream for both input and output  and ofstream for output.  Objects of these classes can be associated with disk files, and we can use their member functions to read and write to the files.  These three classes are declared in the FSTREAM file. [7]
  • 8. Formatted File I/O  In formatted I/O, numbers are stored on disk as a series of characters. Thus 6.02, rather than being stored as a 4-byte type float or an 8-byte type double, is stored as the characters ‘6’, ‘.’, ‘0’, and ‘2’.  This can be inefficient for numbers with many digits, but it’s appropriate in many situations and easy to implement. [8]
  • 9. // writes formatted output to a file // using << operator #include <fstream> // for file I/O #include <iostream> #include <string> #include <stdlib.h> using namespace std; int main() { char ch = 'x'; int j = 77; double d = 6.02; // strings without embedded spaces string str1 = "Rashid"; string str2 = "Farid"; // create ofstream object ofstream outfile("data.txt"); 9 Example 1: Writing Data to a File outfile << ch // insert (write) data << j << ' ' // needs space between numbers << d << str1 << ' ' //needs spaces between strings << str2; cout << "File writtenn"; system("pause"); return 0; } 1 2 [9]
  • 10. Example 1: Writing Data to a File  If the file doesn’t exist, it is created. If it does exist, it is truncated and the new data replaces the old.  The outfile object acts much as cout did in previous programs, so we can use the insertion operator (<<) to output variables of any basic type to the file.  This works because the insertion operator is appropriately overloaded in ostream, from which ofstream is derived.  When the program terminates, the outfile object goes out of scope. This calls its destructor, which closes the file, so we don’t need to close the file explicitly  There are several potential formatting glitches. First, you must separate numbers (such as 77 and 6.02) with nonnumeric characters.  As numbers are stored as a sequence of characters, this is the only way the extraction operator will know, when the data is read back from the file, where one number stops and the next one begins. [10]
  • 11. Example 1: Writing Data to a File  Second, strings must be separated with whitespace for the same reason. This implies that strings cannot contain imbedded blanks.  In this example we use the space character (‘ ‘) for both kinds of delimiters. Characters need no delimiters, since they have a fixed length.  You can verify that program has indeed written the data by examining the DATA.TXT file with the Windows NOTEPAD accessory or the DOS command TYPE. [11]
  • 12. // reads formatted output from a file // using >> operator #include <fstream> // for file I/O #include <iostream> #include <string> #include <stdlib.h> using namespace std; int main() { char ch; int j; double d; string str1, str2; // create ifstream object ifstream infile("data.txt"); //extract (read) data from it infile >> ch >> j >> d >> str1 >> str2; 12 Example 2: Reading Data from a File cout << ch << endl // display the data << j << endl << d << endl << str1 << endl << str2 << endl; system("pause"); return 0; } 1 2 [12]
  • 13.  If you’ve ever used MS-DOS, you are probably familiar with command-line arguments, used when invoking a program. They are typically used to pass the name of a data file to an application. For example, you can invoke a word processor application and the document it will work on at the same time:  C>wordproc afile.doc  Here afile.doc is a command-line argument. How can we get a C++ program to read the command-line arguments? Here’s an example 13 Example 3: Command-Line Arguments #include <iostream> using namespace std; int main(int argc, char* argv[] ) { // number of arguments cout << "argc = " << argc << endl; // display arguments for(int j=0; j<argc; j++) cout << "Argument " << j << " = " << argv[j] << endl; return 0; } [13]
  • 14. Command-Line Arguments  And here’s a sample interaction with the program:  To read command-line arguments, the main() function (don’t forget it’s a function!) must itself be given two arguments. The first, argc (for argument count), represents the total number of command-line arguments. The first command-line argument is always the pathname of the current program. The remaining command-line arguments are those typed by the user; they are delimited by the space character. In the preceding example they are uno, dos, and tres. [14]
  • 15. #include <fstream> // for file #include <iostream> #include <process.h> //for exit() using namespace std; int main(int argc, char* argv[] ) { if( argc != 2 ) { cerr << "Format: oop filename" << endl; exit(-1); } char ch; //character to read ifstream infile; // to read a file infile.open( argv[1] );// open file 15 Example 4: Command-Line Arguments if( !infile ) { // check for errors cerr << "nCan't open " << argv[1]; exit(-1); } while( infile.get(ch) != 0 ) //read a character cout << ch; //display the character return 0; } 1 2 [15]
  • 16. Strings with Embedded Blanks  The technique of our last examples won’t work with char* strings containing embedded blanks.  To handle such strings, you need to write a specific delimiter character after each string, and use the getline()function, rather than the extraction operator, to read them in.  Our next program, outputs some strings with blanks embedded in them. [16]
  • 17. // file output with strings #include <fstream> // for file I/O #include <iostream> #include <stdlib.h> using namespace std; int main() { // create file for output ofstream outfile("data.txt"); //send text to file outfile << "I fear thee, ancient!n"; outfile << "I fear thy skinny handn"; outfile << "And thou art long brown,n"; system("pause"); return 0; } 17 Example 5, 6: Writing and Reading String in a File // file input with strings #include <fstream> // for file I/O #include <iostream> #include <stdlib.h> using namespace std; int main() { const int MAX = 80; // size of buffer char buffer[MAX]; // character buffer // create file for input ifstream infile("data.txt"); while (!infile.eof()){ // until end-of-file // read a line of text infile.getline(buffer, MAX); // display it cout << buffer << endl; } system("pause"); return 0; } 1 2 [17]
  • 18. Writing and Reading String in a File  This program requires all the text lines to terminate with the ‘n’ character, and if you encounter a file in which this is not the case, the program will hang.  The program continues to read one string at a time until it encounters an end-of-file (EOF) condition. The EOF is a signal sent to the program from the operating system when there is no more data to read.  However, checking specifically for an eofbit means that we won’t detect the other error flags, such as the failbit and badbit, which may also occur, although more rarely. To do this, we can change our loop condition: while (infile.good()){ // until any error encountered  You can also test the stream directly. If everything is going well, the object infile returns a nonzero value which is a pointer. Thus we can rewrite our while loop again: while (infile){ // until any error encountered [18]
  • 19. // file output with characters #include <fstream> // for file I/O #include <iostream> #include <stdlib.h> using namespace std; int main() { string str = "Time is a great teacher," " but unfortunately it kills all its" " pupils. Berlioz"; // create file for output ofstream outfile("data.txt"); for (unsigned int j = 0; j < str.size(); j++) // write it to file outfile.put(str[j]); cout << "File writtenn"; system("pause"); return 0; } 19 Example 7, 8: Character I/O // file input with characters #include <fstream> // for file I/O #include <iostream> #include <stdlib.h> using namespace std; int main() { char ch; // character to read // create file for output ifstream infile("data.txt"); // read until the EOF is reached // or an error occurs while (infile){ infile.get(ch); // read a character cout << ch; // display it } cout << endl; system("pause"); return 0; } 1 2 [19]
  • 20. Binary I/O  You can write a few numbers to disk using formatted I/O, but if you’re storing a large amount of numerical data it’s more efficient to use binary I/O, in which numbers are stored as they are in the computer’s RAM memory, rather than as strings of characters.  In binary I/O an int is stored in 4 bytes, whereas its text version might be “12345”, requiring 5 bytes. Similarly, a float is always stored in 4 bytes, while its formatted version might be “6.02314e13”, requiring 10 bytes.  example shows how an array of integers is written to disk and then read back into memory, using binary format.  We use write(), a member of ofstream; and read(), a member of ifstream.  These functions think about data in terms of bytes (type char). They don’t care how the data is formatted, they simply transfer a buffer full of bytes from and to a disk file. [20]
  • 21. // binary input and output with integers #include <fstream> //for file streams #include <iostream> #include <stdlib.h> using namespace std; const int MAX = 100; //size of buffer int buff[MAX]; //buffer for integers int main() { int i; for (i = 0; i < MAX; i++) // fill buffer with data { 0, 1, 2, ... ,99} buff[i] = i; ofstream os("numbers.txt", ios::binary); // create output stream os.write((char*)buff, MAX * sizeof(int)); // write to it os.close(); // must close it for (i =0; i < MAX; i++) // erase buffer buff[i] = 0; ifstream is("numbers.txt", ios::binary); // create input stream is.read((char*)buff, MAX * sizeof(int)); // read from it Example 9: Binary I/O with integers (1/2) [21]
  • 22. for (i = 0; i < MAX; i++) // check data if (buff[i] != i){ cerr << i<< " Data is incorrectn"; return 1; } cout << "Data is correctn"; system("pause"); return 0; } Example 9: Binary I/O with integers (2/2) [22]
  • 23. Object I/O  Since C++ is an object-oriented language, it’s reasonable to wonder how objects can be written to and read from disk.  The next examples show the process  When writing an object, we generally want to use binary mode. This writes the same bit configuration to disk that was stored in memory, and ensures that numerical data contained in objects is handled properly.  Here’s the listing for OPERS, which asks the user for information about an object of class person, and then writes this object to the disk file PERSON.DAT [23]
  • 24. #include <fstream> // for file streams #include <iostream> using namespace std; class person { // class of persons protected: char name[80]; // person’s name short age; // person’s age public: void getData() { //get person’s data cout << "Enter name : "; cin.get(name,80); cout << "Enter age : " ; cin >> age; } }; int main() { person pr1; // create a person pr1.getData(); // get data for person 1 ofstream outfile("PERSON.DAT", ios::binary); // create ofstream object outfile.write((char*) &pr1, sizeof(pr1)); // write to it return 0; } Example 10: Writing Object to a File [24]
  • 25. // saves person object to disk #include <fstream> // for file streams #include <iostream> using namespace std; class person { protected: char name[80]; // person’s name short age; // person’s age public: void showData() { // display person’s data cout << "Name: " << name << endl; cout << "Age : " << age << endl; } }; int main() { person pr1; // create a person ifstream infile("PERSON.DAT", ios::binary); infile.read((char*) &pr1, sizeof(pr1)); // read from file pr1.showData(); return 0; } Example 10: Reading Object from a File [25]
  • 26. istream Functions [26] Function Purpose >> Formatted extraction for all basic (and overloaded) types. get(ch) Extract one character into ch. getline(str, MAX) Extract one line into array str, until MAX characters or the ‘n’ character getline(str, MAX, DELIM) Extract characters into array str, until MAX characters or the DELIM character. putback(ch) Insert last character read back into input stream. ignore(MAX, ‘n’) Extract and discard up to MAX characters until (and including) the specified delimiter ‘n’. ch = stream.peek( ) Read one character, leave it in stream. read(str, MAX) For files, extract up to MAX characters into str, until EOF. seekg(n) Set distance (n bytes) of file pointer from start of file. e.g. infile.seekg(0, ios::end); // go to 0 bytes from end seekg(pos, seek_dir) Set distance (in bytes) of file pointer from specified place in file. seek_dir can be ios::beg, ios::cur, ios::end. tellg( ) Return position (in bytes) of file pointer from start of file. e.g. int endposition = infile.tellg();
  • 27. ostream Functions [27] Function Purpose << Formatted insertion for all basic (and overloaded) types. put(ch) Insert one character ch into stream. flush() Flush buffer contents and Insert newline. write(str, SIZE) Insert SIZE characters from array str into file. seekp(n) Set distance in n bytes of file pointer from start of file. seekp(pos, seek_dir) Set distance (in bytes) of file pointer from specified place in file. seek_dir can be ios::beg, ios::cur, ios::end. tellgp( ) Return position (in bytes) of file pointer from start of file. e.g. int endposition = outfile.tellg();
  • 28. #include <fstream> // for file streams #include <iostream> using namespace std; class Book { protected: char title[80]; char auther[80]; double price; public: void Add_Record(); void Read_All(); void Search(); void Delete(); }; Example 11: Books Management System (1/8) [28]
  • 29. void Book::Add_Record() { cout << "Enter title : "; // eat chars, including newline cin.ignore(80, 'n'); cin.getline(title, 80); cout << "Enter Auther : "; cin.getline(auther, 80); cout << "Enter Price : "; cin >> price; cout << "Title = " << title << endl; cout << "Auther = " << auther << endl; cout << "Price = " << price << endl; ofstream outfile; outfile.open("books.txt", std::ios_base::app); outfile << title << "" << auther << "" << price << endl; system("pause"); } Example 11: Books Management System (2/8) [29]
  • 30. void Book::Read_All() { system("CLS"); const int MAX = 240; int S_No = 0; char buffer[MAX]; // character buffer ifstream infile("books.txt"); while (infile) { infile.getline(buffer, MAX); if (strlen(buffer) > 0) { const char* delim = ""; char* next_token; char* title = strtok_s(buffer, delim, &next_token); char* auther = strtok_s(NULL, delim, &next_token); char* prc = strtok_s(NULL, delim, &next_token); cout << "#" << ++S_No << endl; cout << " Title = " << title << endl; cout << " Auther = " << auther << endl; cout << " Price = " << prc << endl; } } } Example 11: Books Management System (3/8) [30]
  • 31. void Book::Search() { int S_No = 0; cout << "Enter title to Search: "; // eat chars, including newline cin.ignore(80, 'n'); cin.getline(this->title, 80); system("CLS"); const int MAX = 240; // size of buffer char buffer[MAX]; // character buffer ifstream infile("books.txt"); while (infile) { infile.getline(buffer, MAX); if (strlen(buffer) > 0) { const char* delim = ""; char* next_token; char* title = strtok_s(buffer, delim, &next_token); char* auther = strtok_s(NULL, delim, &next_token); char* prc = strtok_s(NULL, delim, &next_token); char* output = strstr(title, this->title); Example 11: Books Management System (4/8) [31]
  • 32. S_No++; if (output) { cout << "#" << S_No << endl; cout << "Title = " << title << endl; cout << "Auther = " << auther << endl; cout << "Price = " << prc << endl; cout << "_________________________________" << endl; } } } } void Book::Delete() { system("CLS"); const int MAX = 240; // size of buffer int R_No = 0, S_No = 0; cout << "Please Enter Record Number: "; cin >> R_No; char buffer[MAX]; // character buffer ifstream infile("books.txt"); ofstream outfile("temp.txt"); Example 11: Books Management System (5/8) [32]
  • 33. while (infile) { infile.getline(buffer, MAX); if (strlen(buffer) > 0) { const char* delim = ""; char* next_token; char* title = strtok_s(buffer, delim, &next_token); char* auther = strtok_s(NULL, delim, &next_token); char* prc = strtok_s(NULL, delim, &next_token); S_No++; if (S_No == R_No) { char choice; cout << "#" << S_No << endl; cout << " Title = " << title << endl; cout << " Auther = " << auther << endl; cout << " Price = " << prc << endl; cout << "Do you want to Delete this Record [y/n]?: "; cin >> choice; if (choice == 'y') continue; Example 11: Books Management System (6/8) [33]
  • 34. else outfile << title << "" << auther << "" << prc << endl; } else outfile << title << "" << auther << "" << prc << endl; } } infile.close(); outfile.close(); remove("books.txt"); rename("temp.txt", "books.txt"); } int main() { Book b; while (1) { char choice; cout << "[Operations]" << endl; cout << "A - Add" << endl; cout << "D - Delete" << endl; Example 11: Books Management System (7/8) [34]
  • 35. cout << "R - Read All" << endl; cout << "S - Search Title" << endl; cout << "Q - Quit " << endl; cin >> choice; switch (choice) { case 'A': case 'a': b.Add_Record(); break; case 'D': case 'd': b.Delete(); break; case 'R': case 'r': b.Read_All(); break; case 'S': case 's': b.Search(); break; case 'Q': case 'q': exit(0); default: cout << "Wrong Choice" << endl; } } return 0; } Example 11: Books Management System (8/8) [35]