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]
Ad

Recommended

Stream classes in C++
Stream classes in C++
Shyam Gupta
 
streams and files
streams and files
Mariam Butt
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
Basics of file handling
Basics of file handling
pinkpreet_kaur
 
basics of file handling
basics of file handling
pinkpreet_kaur
 
File management in C++
File management in C++
apoorvaverma33
 
file_handling_in_c.ppt......................................
file_handling_in_c.ppt......................................
nadoj47203
 
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
SanskritiGupta39
 
File handling in_c
File handling in_c
sanya6900
 
Introduction to files management systems
Introduction to files management systems
araba8
 
Data file handling
Data file handling
TAlha MAlik
 
17 files and streams
17 files and streams
Docent Education
 
Managing console i/o operation,working with files
Managing console i/o operation,working with files
ramya marichamy
 
Managing,working with files
Managing,working with files
kirupasuchi1996
 
File handling in c++
File handling in c++
Daniel Nyagechi
 
File in cpp 2016
File in cpp 2016
Dr .Ahmed Tawwab
 
Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
C++ - 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++
Kulachi Hansraj Model School Ashok Vihar
 
file.ppt
file.ppt
DeveshDewangan5
 
Ds lec 14 filing in c++
Ds lec 14 filing in c++
Taimoor Suleman
 
C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Files in c++
Files in c++
Selvin Josy Bai Somu
 
Unit5 C
Unit5 C
arnold 7490
 
13 file handling in C++.pptx oops object oriented programming
13 file handling in C++.pptx oops object oriented programming
archana22486y
 
OS Lab 04.pdfgsxdfxxxxxxxxgddfsfgxgfxfxcgfxgf
OS Lab 04.pdfgsxdfxxxxxxxxgddfsfgxgfxfxcgfxgf
SamraNawabi
 
DOC-20241121-WA0004bwushshusjssjuwh..pdf
DOC-20241121-WA0004bwushshusjssjuwh..pdf
TanishaWaichal
 
DBMS: Week 15 - Database Security and Access Control
DBMS: Week 15 - Database Security and Access Control
RashidFaridChishti
 
DBMS: Week 14 - Backup and Recovery in MySQL
DBMS: Week 14 - Backup and Recovery in MySQL
RashidFaridChishti
 

More Related Content

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

File handling in_c
File handling in_c
sanya6900
 
Introduction to files management systems
Introduction to files management systems
araba8
 
Data file handling
Data file handling
TAlha MAlik
 
17 files and streams
17 files and streams
Docent Education
 
Managing console i/o operation,working with files
Managing console i/o operation,working with files
ramya marichamy
 
Managing,working with files
Managing,working with files
kirupasuchi1996
 
File handling in c++
File handling in c++
Daniel Nyagechi
 
File in cpp 2016
File in cpp 2016
Dr .Ahmed Tawwab
 
Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
C++ - 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++
Kulachi Hansraj Model School Ashok Vihar
 
file.ppt
file.ppt
DeveshDewangan5
 
Ds lec 14 filing in c++
Ds lec 14 filing in c++
Taimoor Suleman
 
C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Files in c++
Files in c++
Selvin Josy Bai Somu
 
Unit5 C
Unit5 C
arnold 7490
 
13 file handling in C++.pptx oops object oriented programming
13 file handling in C++.pptx oops object oriented programming
archana22486y
 
OS Lab 04.pdfgsxdfxxxxxxxxgddfsfgxgfxfxcgfxgf
OS Lab 04.pdfgsxdfxxxxxxxxgddfsfgxgfxfxcgfxgf
SamraNawabi
 
DOC-20241121-WA0004bwushshusjssjuwh..pdf
DOC-20241121-WA0004bwushshusjssjuwh..pdf
TanishaWaichal
 
File handling in_c
File handling in_c
sanya6900
 
Introduction to files management systems
Introduction to files management systems
araba8
 
Data file handling
Data file handling
TAlha MAlik
 
Managing console i/o operation,working with files
Managing console i/o operation,working with files
ramya marichamy
 
Managing,working with files
Managing,working with files
kirupasuchi1996
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
ANUSUYA S
 
C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
13 file handling in C++.pptx oops object oriented programming
13 file handling in C++.pptx oops object oriented programming
archana22486y
 
OS Lab 04.pdfgsxdfxxxxxxxxgddfsfgxgfxfxcgfxgf
OS Lab 04.pdfgsxdfxxxxxxxxgddfsfgxgfxfxcgfxgf
SamraNawabi
 
DOC-20241121-WA0004bwushshusjssjuwh..pdf
DOC-20241121-WA0004bwushshusjssjuwh..pdf
TanishaWaichal
 

More from RashidFaridChishti (20)

DBMS: Week 15 - Database Security and Access Control
DBMS: Week 15 - Database Security and Access Control
RashidFaridChishti
 
DBMS: Week 14 - Backup and Recovery in MySQL
DBMS: Week 14 - Backup and Recovery in MySQL
RashidFaridChishti
 
DBMS: Week 13 - Transactions and Concurrency Control
DBMS: Week 13 - Transactions and Concurrency Control
RashidFaridChishti
 
DBMS: Week 12 - Triggers in MySQL Database Server
DBMS: Week 12 - Triggers in MySQL Database Server
RashidFaridChishti
 
DBMS: Week 11 - Stored Procedures and Functions
DBMS: Week 11 - Stored Procedures and Functions
RashidFaridChishti
 
DBMS: Week 10 - Database Design and Normalization
DBMS: Week 10 - Database Design and Normalization
RashidFaridChishti
 
DBMS: Week 09 - SQL Constraints and Indexing
DBMS: Week 09 - SQL Constraints and Indexing
RashidFaridChishti
 
DBMS: Week 08 - Joins and Views in MySQL
DBMS: Week 08 - Joins and Views in MySQL
RashidFaridChishti
 
DBMS: Week 07 - Advanced SQL Queries in MySQL
DBMS: Week 07 - Advanced SQL Queries in MySQL
RashidFaridChishti
 
DBMS: Week 06 - SQL - Data Manipulation Language (DML)
DBMS: Week 06 - SQL - Data Manipulation Language (DML)
RashidFaridChishti
 
DBMS: Week 05 - Introduction to SQL Query
DBMS: Week 05 - Introduction to SQL Query
RashidFaridChishti
 
DBMS: Week 04 - Relational Model in a Database
DBMS: Week 04 - Relational Model in a Database
RashidFaridChishti
 
DBMS: Week 03 - Data Models and ER Model
DBMS: Week 03 - Data Models and ER Model
RashidFaridChishti
 
DBMS: Week 02 - Database System Architecture
DBMS: Week 02 - Database System Architecture
RashidFaridChishti
 
DBMS: Week 01 - Introduction to Databases
DBMS: Week 01 - Introduction to Databases
RashidFaridChishti
 
Lab 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.docx
RashidFaridChishti
 
Lab 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.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
DBMS: Week 15 - Database Security and Access Control
DBMS: Week 15 - Database Security and Access Control
RashidFaridChishti
 
DBMS: Week 14 - Backup and Recovery in MySQL
DBMS: Week 14 - Backup and Recovery in MySQL
RashidFaridChishti
 
DBMS: Week 13 - Transactions and Concurrency Control
DBMS: Week 13 - Transactions and Concurrency Control
RashidFaridChishti
 
DBMS: Week 12 - Triggers in MySQL Database Server
DBMS: Week 12 - Triggers in MySQL Database Server
RashidFaridChishti
 
DBMS: Week 11 - Stored Procedures and Functions
DBMS: Week 11 - Stored Procedures and Functions
RashidFaridChishti
 
DBMS: Week 10 - Database Design and Normalization
DBMS: Week 10 - Database Design and Normalization
RashidFaridChishti
 
DBMS: Week 09 - SQL Constraints and Indexing
DBMS: Week 09 - SQL Constraints and Indexing
RashidFaridChishti
 
DBMS: Week 08 - Joins and Views in MySQL
DBMS: Week 08 - Joins and Views in MySQL
RashidFaridChishti
 
DBMS: Week 07 - Advanced SQL Queries in MySQL
DBMS: Week 07 - Advanced SQL Queries in MySQL
RashidFaridChishti
 
DBMS: Week 06 - SQL - Data Manipulation Language (DML)
DBMS: Week 06 - SQL - Data Manipulation Language (DML)
RashidFaridChishti
 
DBMS: Week 05 - Introduction to SQL Query
DBMS: Week 05 - Introduction to SQL Query
RashidFaridChishti
 
DBMS: Week 04 - Relational Model in a Database
DBMS: Week 04 - Relational Model in a Database
RashidFaridChishti
 
DBMS: Week 03 - Data Models and ER Model
DBMS: Week 03 - Data Models and ER Model
RashidFaridChishti
 
DBMS: Week 02 - Database System Architecture
DBMS: Week 02 - Database System Architecture
RashidFaridChishti
 
DBMS: Week 01 - Introduction to Databases
DBMS: Week 01 - Introduction to Databases
RashidFaridChishti
 
Lab 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.docx
RashidFaridChishti
 
Lab 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.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
Ad

Recently uploaded (20)

Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
60 Years and Beyond eBook 1234567891.pdf
60 Years and Beyond eBook 1234567891.pdf
waseemalazzeh
 
NALCO Green Anode Plant,Compositions of CPC,Pitch
NALCO Green Anode Plant,Compositions of CPC,Pitch
arpitprachi123
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
ElysiumPro Company Profile 2025-2026.pdf
ElysiumPro Company Profile 2025-2026.pdf
info751436
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Cadastral Maps
Cadastral Maps
Google
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
KhadijaKhadijaAouadi
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
60 Years and Beyond eBook 1234567891.pdf
60 Years and Beyond eBook 1234567891.pdf
waseemalazzeh
 
NALCO Green Anode Plant,Compositions of CPC,Pitch
NALCO Green Anode Plant,Compositions of CPC,Pitch
arpitprachi123
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
ElysiumPro Company Profile 2025-2026.pdf
ElysiumPro Company Profile 2025-2026.pdf
info751436
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Cadastral Maps
Cadastral Maps
Google
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
IPL_Logic_Flow.pdf Mainframe IPLMainframe IPL
KhadijaKhadijaAouadi
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Ad

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]