SlideShare a Scribd company logo
Files and Streams
09/04/131 VIT - SCSE
By
G.SasiKumar., M.E., (Ph.D).,
Assistant Professor
School of Computing Science and Engineering
VIT University
09/04/132 VIT - SCSE
Files
Diskette
Memory
Input file
Output file
Used to transfer data to and from disk
09/04/133 VIT - SCSE
Streams
ď‚—Stream
ď‚—a channel or medium where data are passed to receivers from
senders.
ď‚—Output Stream
ď‚—a channel where data are sent out to a receiver
ď‚—cout; the standard output stream (to monitor)
ď‚—the monitor is a destination device
ď‚—Input Stream
ď‚—a channel where data are received from a sender
ď‚—cin; the standard input stream (from the keyboard)
ď‚—the keyboard is a source device
09/04/134 VIT - SCSE
Standard Input / Output Streams
ď‚—Standard Streams use #include <iostream.h>
ď‚—Standard Input Stream
ď‚—cin names the stream
ď‚—the extractor operator >> extracts, gets, or receives the next element from the
stream
ď‚—Standard Output Stream
ď‚—cout names the stream
ď‚—the inserter operator << inserts, puts, or sends the next element to the stream
ď‚—Opening & closing of the standard streams occur automatically when
the program begins & ends.
09/04/135 VIT - SCSE
File Streams
ď‚—Files
ď‚—data structures that are stored separately from the program (using
auxiliary memory)
ď‚—streams must be connected to these files
ď‚—Input File Stream
ď‚—extracts, receives, or gets data from the file
ď‚—Output File Stream
ď‚—inserts, sends, or puts data to the file
ď‚—#include <fstream.h> creates two new classes
ď‚—ofstream (output file stream)
ď‚—ifstream (input file stream)
09/04/136 VIT - SCSE
C++ Files and Streams
ď‚—C++ views each files as a sequence of bytes.
ď‚—Each file ends with an end-of-file marker.
ď‚—When a file is opened, an object is created and a stream is
associated with the object.
ď‚—To perform file processing in C++, the header files
<iostream.h> and <fstream.h> must be included.
ď‚—<fstream.> includes <ifstream> and <ofstream>
09/04/137 VIT - SCSE
09/04/138 VIT - SCSE
File Handling Classes
Hierarchy Diagram
09/04/139 VIT - SCSE
iosios
streambufstreambuf ostreamostreamistreamistream
iostreamiostream
fstreamfstream
filebuffilebuf
ofstreamofstreamifstreamifstream
fstreambasefstreambase
09/04/1310 VIT - SCSE
Opening Files
ď‚—Use open function or include file name when declaring
variable:
ď‚—ifstream inobj1;
inobj1.open(“in1.dat”)
ifstream inobj2(“in2.dat”);
ď‚—To check if file successfully opened check object in
condition:
ď‚—if (!inobj1)
 cout << “Unable to open file in1.dat” << endl;
09/04/1311 VIT - SCSE
Opening Output Files
Ofstream outClientFile(“clients.dat”, ios:out)
OR
Ofstream outClientFile;
outClientFile.open(“clients.dat”, ios:out)
Example
ofstream out(“outf”,ios::out | ios::append);
// out is an append connection to outf
09/04/1312 VIT - SCSE
File Open Modes
ios:: app - (append) write all output to the end of file
ios:: ate - data can be written anywhere in the file
ios:: binary - read/write data in binary format
ios:: in - (input) open a file for input
ios::out - (output) open a file for output
ios: trunc -(truncate) discard the files’ contents if
it exists
ios:nocreate - if the file does NOT exists, the open operation fails
ios:noreplace - if the file exists, the open operation fails
09/04/1313 VIT - SCSE
Closing a File
ď‚—Use close() on object to close connection to file:
ifstream in(“in.dat”);
…
ď‚—in.close();
09/04/1314 VIT - SCSE
#include <stdlib.h>
#include <iostream.h>
#include <fstream.h>
void main() {
char infname[101];
char outfname[101];
char buffer[101];
cout << ”File to copy from: ";
cin >> infname;
ifstream in(infname);
if (!in) {
cout << "Unable to open " << infname
<< endl;
exit(0);
}
cout << "File to copy to: ";
cin >> outfname;
ofstream out(outfname,ios::out |
ios::noreplace);
if (!out) {
cout << "Unable to open " <<
outfname << " -- already exists!" <<
endl;
exit(0);
}
in.getline(buffer,100);
while (!in.eof()) {
out << buffer << endl;
in.getline(buffer,100);
}
in.close();
out.close();
}
Using Sequential Access Files
ď‚—A sequential access file is often called a text file
ď‚— Bit - smallest data item
ď‚—value of 0 or 1
 Byte – 8 bits
ď‚— used to store a character
ď‚— Decimal digits, letters, and special symbols
ď‚— Field - group of characters conveying meaning
ď‚—Example: your name
 Record – group of related fields
ď‚—Represented a struct or a class
ď‚—Example: In a payroll system, a record for a particular employee that
contained his/her identification number, name, address, etc.
 File – group of related records
ď‚—Example: payroll file
 Database – group of related files
09/04/1315 VIT - SCSE
09/04/1316 VIT - SCSE
The Data Hierarchy
ď‚—Record key
ď‚—identifies a record to facilitate the retrieval of specific records from a file
ď‚—Sequential file
ď‚— records typically sorted by key
1
01001010
Judy
Judy Green
Sally Black
Tom Blue
Judy Green
Iris Orange
Randy Red
File
Record
Field
Byte (ASCII character J)
Bit
09/04/1317 VIT - SCSE
Files and Streams
ď‚—C++ views each file as a sequence of bytes
ď‚—File ends with the end-of-file marker
ď‚—Stream created when a file is opened
ď‚—File processing
ď‚—Headers <iostream.h> (cout, cin, cerr, clog)
ď‚—and <fstream.h>
ď‚—class ifstream - input
ď‚—class ofstream - output
ď‚—class fstream - either input or output
09/04/1318
VIT - SCSE
Creating a Sequential Access
File
ď‚—Files are opened by creating objects of stream classes
ifstream, ofstream or fstream
ď‚—File stream member functions for object file:
file.open(“Filename”, fileOpenMode);
ď‚—file.close();
ď‚—destructor automatically closes file if not explicitly closed
ď‚—File open modes:
Mode Description
ios::app Write all output to the end of the file.
ios::ate Open a file for output and move to the end of the
file (normally used to append data to a file).
Data can be written anywhere in the file.
ios::in Open a file for input.
ios::out Open a file for output.
ios::trunc Discard the file’s contents if it exists (this is
also the default action for ios::out)
ios::binary Open a file for binary (i.e., non-text) input or
output.
Makes a "line of
communication"
with the object and
the file.
09/04/1319 VIT - SCSE
File position pointer
<istream> and <ostream> classes provide member functions for
repositioning the file pointer (the byte number of the next byte
in the file to be read or to be written.)
These member functions are:
seekg (seek get) for istream class
seekp (seek put) for ostream class
09/04/1320
VIT - SCSE
Examples of moving a file
pointer
inClientFile.seekg(0) - repositions the file get pointer to the beginning
of the file
inClientFile.seekg(n, ios:beg) - repositions the file get pointer to the
n-th byte of the file
inClientFile.seekg(m, ios:end) -repositions the file get pointer to the
m-th byte from the end of file
nClientFile.seekg(0, ios:end) - repositions the file get pointer to the
end of the file
The same operations can be performed with <ostream>
function member seekp.
09/04/1321
VIT - SCSE
Member functions tellg() and
tellp().
Member functions tellg and tellp are provided to return the
current locations of the get and put pointers, respectively.
long location = inClientFile.tellg();
To move the pointer relative to the current location use ios:cur
inClientFile.seekg(n, ios:cur) - moves the file get pointer n bytes
forward.
09/04/1322
VIT - SCSE
Updating a sequential file
Data that is formatted and written to a sequential file cannot
be modified easily without the risk of destroying other data
in the file.
If we want to modify a record of data, the new data may be
longer than the old one and it could overwrite parts of the
record following it.
Problems with sequential files
Sequential files are inappropriate for so-called “instant access”
applications in which a particular record of information must
be located immediately.
These applications include banking systems, point-of-sale
systems, airline reservation systems, (or any data-base
system.)
09/04/1323
VIT - SCSE
Random access files
Instant access is possible with random access files.
Individual records of a random access file can be accessed
directly (and quickly) without searching many other
records.
09/04/1324
VIT - SCSE
Creating a Random Access
Fileď‚—write - outputs a fixed number of bytes beginning at a
specific location in memory to the specified stream
ď‚—When writing an integer number to a file,
ď‚—outFile.write( reinterpret_cast<const char *>( &number ),
sizeof( number ) );
ď‚—First argument: pointer of type const char * (location to
write from)
ď‚—address of number cast into a pointer
ď‚—Second argument: number of bytes to write(sizeof(number))
ď‚—recall that data is represented internally in binary (thus, integers can be
stored in 4 bytes)
ď‚—Do not use
ď‚—outFile << number;
ď‚—could print 1 to 11 digits, each digit taking up a byte of storage
09/04/1325
VIT - SCSE
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit.dat", ios::ate );
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
cout << "Enter account number "
<< "(1 to 100, 0 to end input)n? ";
clientData client;
cin >> client.accountNumber;
while ( client.accountNumber > 0 &&
client.accountNumber <= 100 )
{
cout << "Enter lastname, firstname, balancen?
";
cin >> client.lastName >> client.firstName
>> client.balance;
outCredit.seekp( ( client.accountNumber - 1 ) *
sizeof( clientData ) );
outCredit.write(
reinterpret_cast<const char *>( &client ),
sizeof( clientData ) );
cout << "Enter account numbern? ";
cin >> client.accountNumber;
}
return 0;
}
09/04/1326
VIT - SCSE
Writing Data Randomly to a
Random Access File
ď‚—seekp can be used in combination with write to store data
at exact locations in an output file
09/04/1327
VIT - SCSE
Reading data from a random file
#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
void outputLine( ostream&, const clientData & );
int main()
{
ifstream inCredit( "credit.dat", ios::in );
if ( !inCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
cout << setiosflags( ios::left ) << setw( 10 ) <<
"Account"
<< setw( 16 ) << "Last Name" << setw( 11 )
<< "First Name" << resetiosflags( ios::left )
<< setw( 10 ) << "Balance" << endl;
clientData client;
inCredit.read( reinterpret_cast<char
*>( &client ),
sizeof( clientData ) );
while ( inCredit && !inCredit.eof() ) {
if ( client.accountNumber != 0 )
outputLine( cout, client );
inCredit.read( reinterpret_cast<char
*>( &client ),
sizeof( clientData ) );
}
return 0;
}
void outputLine( ostream &output, const clientData &c )
{
output << setiosflags( ios::left ) << setw( 10 )
<< c.accountNumber << setw( 16 ) <<
c.lastName
<< setw( 11 ) << c.firstName << setw( 10 )
<< setprecision( 2 ) << resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< c.balance << 'n';
}
09/04/1328
VIT - SCSE
The <istream> function read
inCredit.read (reinterpret_cast<char *>(&client),
sizeof(clientData));
The <istream> function inputs a specified (by
sizeof(clientData)) number of bytes from the current
position of the specified stream into an object.
09/04/1329
VIT - SCSE

More Related Content

What's hot

Cpp file-handling
Cpp file-handlingCpp file-handling
Cpp file-handling
JiaahRajpout123
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
krishna partiwala
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
Data file handling
Data file handlingData file handling
Data file handlingTAlha MAlik
 
Files in c++
Files in c++Files in c++
Files in c++
NivethaJeyaraman
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
Papu Kumar
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
Haresh Jaiswal
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
ProfSonaliGholveDoif
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
Khushal Mehta
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
indra Kishor
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
HalaiHansaika
 

What's hot (20)

Cpp file-handling
Cpp file-handlingCpp file-handling
Cpp file-handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File Pointers
File PointersFile Pointers
File Pointers
 
Data file handling
Data file handlingData file handling
Data file handling
 
Files in c++
Files in c++Files in c++
Files in c++
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
file handling c++
file handling c++file handling c++
file handling c++
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 

Similar to 17 files and streams

new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
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
 
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
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
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
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
anuvayalil5525
 
File management in C++
File management in C++File management in C++
File management in C++
apoorvaverma33
 
File Organization
File OrganizationFile Organization
File Organization
RAMPRAKASH REDDY ARAVA
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handlingDeepak Singh
 
File Handling
File HandlingFile Handling
File Handling
TusharBatra27
 
data file handling
data file handlingdata file handling
data file handling
krishna partiwala
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
System calls operating system ppt by rohit malav
System calls operating system  ppt by rohit malavSystem calls operating system  ppt by rohit malav
System calls operating system ppt by rohit malav
Rohit malav
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
Venugopalavarma Raja
 
Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-files
cskvsmi44
 

Similar to 17 files and streams (20)

new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
 
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
 
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
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
working with files
working with filesworking with files
working with files
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
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
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
File management in C++
File management in C++File management in C++
File management in C++
 
File Organization
File OrganizationFile Organization
File Organization
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
File Handling
File HandlingFile Handling
File Handling
 
data file handling
data file handlingdata file handling
data file handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
System calls operating system ppt by rohit malav
System calls operating system  ppt by rohit malavSystem calls operating system  ppt by rohit malav
System calls operating system ppt by rohit malav
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-files
 

More from Docent Education

16 virtual function
16 virtual function16 virtual function
16 virtual function
Docent Education
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
Docent Education
 
13 exception handling
13 exception handling13 exception handling
13 exception handling
Docent Education
 
12 constructors invocation and data members initialization
12 constructors invocation and data members initialization12 constructors invocation and data members initialization
12 constructors invocation and data members initialization
Docent Education
 
12 constructors invocation and data members initialization
12 constructors invocation and data members initialization12 constructors invocation and data members initialization
12 constructors invocation and data members initialization
Docent Education
 
11 constructors in derived classes
11 constructors in derived classes11 constructors in derived classes
11 constructors in derived classes
Docent Education
 
10 inheritance
10 inheritance10 inheritance
10 inheritance
Docent Education
 
7 class objects
7 class objects7 class objects
7 class objects
Docent Education
 
6 pointers functions
6 pointers functions6 pointers functions
6 pointers functions
Docent Education
 
5 array
5 array5 array
5 array
Docent Education
 
4 Type conversion functions
4 Type conversion functions4 Type conversion functions
4 Type conversion functions
Docent Education
 
1 Intro Object Oriented Programming
1  Intro Object Oriented Programming1  Intro Object Oriented Programming
1 Intro Object Oriented Programming
Docent Education
 
3 intro basic_elements
3 intro basic_elements3 intro basic_elements
3 intro basic_elements
Docent Education
 
2 Intro c++
2 Intro c++2 Intro c++
2 Intro c++
Docent Education
 
unit-1-intro
 unit-1-intro unit-1-intro
unit-1-intro
Docent Education
 

More from Docent Education (15)

16 virtual function
16 virtual function16 virtual function
16 virtual function
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
13 exception handling
13 exception handling13 exception handling
13 exception handling
 
12 constructors invocation and data members initialization
12 constructors invocation and data members initialization12 constructors invocation and data members initialization
12 constructors invocation and data members initialization
 
12 constructors invocation and data members initialization
12 constructors invocation and data members initialization12 constructors invocation and data members initialization
12 constructors invocation and data members initialization
 
11 constructors in derived classes
11 constructors in derived classes11 constructors in derived classes
11 constructors in derived classes
 
10 inheritance
10 inheritance10 inheritance
10 inheritance
 
7 class objects
7 class objects7 class objects
7 class objects
 
6 pointers functions
6 pointers functions6 pointers functions
6 pointers functions
 
5 array
5 array5 array
5 array
 
4 Type conversion functions
4 Type conversion functions4 Type conversion functions
4 Type conversion functions
 
1 Intro Object Oriented Programming
1  Intro Object Oriented Programming1  Intro Object Oriented Programming
1 Intro Object Oriented Programming
 
3 intro basic_elements
3 intro basic_elements3 intro basic_elements
3 intro basic_elements
 
2 Intro c++
2 Intro c++2 Intro c++
2 Intro c++
 
unit-1-intro
 unit-1-intro unit-1-intro
unit-1-intro
 

Recently uploaded

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 

Recently uploaded (20)

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 

17 files and streams

  • 1. Files and Streams 09/04/131 VIT - SCSE By G.SasiKumar., M.E., (Ph.D)., Assistant Professor School of Computing Science and Engineering VIT University
  • 2. 09/04/132 VIT - SCSE Files Diskette Memory Input file Output file Used to transfer data to and from disk
  • 3. 09/04/133 VIT - SCSE Streams ď‚—Stream ď‚—a channel or medium where data are passed to receivers from senders. ď‚—Output Stream ď‚—a channel where data are sent out to a receiver ď‚—cout; the standard output stream (to monitor) ď‚—the monitor is a destination device ď‚—Input Stream ď‚—a channel where data are received from a sender ď‚—cin; the standard input stream (from the keyboard) ď‚—the keyboard is a source device
  • 4. 09/04/134 VIT - SCSE Standard Input / Output Streams ď‚—Standard Streams use #include <iostream.h> ď‚—Standard Input Stream ď‚—cin names the stream ď‚—the extractor operator >> extracts, gets, or receives the next element from the stream ď‚—Standard Output Stream ď‚—cout names the stream ď‚—the inserter operator << inserts, puts, or sends the next element to the stream ď‚—Opening & closing of the standard streams occur automatically when the program begins & ends.
  • 5. 09/04/135 VIT - SCSE File Streams ď‚—Files ď‚—data structures that are stored separately from the program (using auxiliary memory) ď‚—streams must be connected to these files ď‚—Input File Stream ď‚—extracts, receives, or gets data from the file ď‚—Output File Stream ď‚—inserts, sends, or puts data to the file ď‚—#include <fstream.h> creates two new classes ď‚—ofstream (output file stream) ď‚—ifstream (input file stream)
  • 6. 09/04/136 VIT - SCSE C++ Files and Streams ď‚—C++ views each files as a sequence of bytes. ď‚—Each file ends with an end-of-file marker. ď‚—When a file is opened, an object is created and a stream is associated with the object. ď‚—To perform file processing in C++, the header files <iostream.h> and <fstream.h> must be included. ď‚—<fstream.> includes <ifstream> and <ofstream>
  • 8. 09/04/138 VIT - SCSE File Handling Classes Hierarchy Diagram
  • 9. 09/04/139 VIT - SCSE iosios streambufstreambuf ostreamostreamistreamistream iostreamiostream fstreamfstream filebuffilebuf ofstreamofstreamifstreamifstream fstreambasefstreambase
  • 10. 09/04/1310 VIT - SCSE Opening Files ď‚—Use open function or include file name when declaring variable: ď‚—ifstream inobj1; ď‚—inobj1.open(“in1.dat”) ď‚—ifstream inobj2(“in2.dat”); ď‚—To check if file successfully opened check object in condition: ď‚—if (!inobj1) ď‚— cout << “Unable to open file in1.dat” << endl;
  • 11. 09/04/1311 VIT - SCSE Opening Output Files Ofstream outClientFile(“clients.dat”, ios:out) OR Ofstream outClientFile; outClientFile.open(“clients.dat”, ios:out) Example ofstream out(“outf”,ios::out | ios::append); // out is an append connection to outf
  • 12. 09/04/1312 VIT - SCSE File Open Modes ios:: app - (append) write all output to the end of file ios:: ate - data can be written anywhere in the file ios:: binary - read/write data in binary format ios:: in - (input) open a file for input ios::out - (output) open a file for output ios: trunc -(truncate) discard the files’ contents if it exists ios:nocreate - if the file does NOT exists, the open operation fails ios:noreplace - if the file exists, the open operation fails
  • 13. 09/04/1313 VIT - SCSE Closing a File ď‚—Use close() on object to close connection to file: ď‚—ifstream in(“in.dat”); … ď‚—in.close();
  • 14. 09/04/1314 VIT - SCSE #include <stdlib.h> #include <iostream.h> #include <fstream.h> void main() { char infname[101]; char outfname[101]; char buffer[101]; cout << ”File to copy from: "; cin >> infname; ifstream in(infname); if (!in) { cout << "Unable to open " << infname << endl; exit(0); } cout << "File to copy to: "; cin >> outfname; ofstream out(outfname,ios::out | ios::noreplace); if (!out) { cout << "Unable to open " << outfname << " -- already exists!" << endl; exit(0); } in.getline(buffer,100); while (!in.eof()) { out << buffer << endl; in.getline(buffer,100); } in.close(); out.close(); }
  • 15. Using Sequential Access Files ď‚—A sequential access file is often called a text file ď‚— Bit - smallest data item ď‚—value of 0 or 1 ď‚— Byte – 8 bits ď‚— used to store a character ď‚— Decimal digits, letters, and special symbols ď‚— Field - group of characters conveying meaning ď‚—Example: your name ď‚— Record – group of related fields ď‚—Represented a struct or a class ď‚—Example: In a payroll system, a record for a particular employee that contained his/her identification number, name, address, etc. ď‚— File – group of related records ď‚—Example: payroll file ď‚— Database – group of related files 09/04/1315 VIT - SCSE
  • 16. 09/04/1316 VIT - SCSE The Data Hierarchy ď‚—Record key ď‚—identifies a record to facilitate the retrieval of specific records from a file ď‚—Sequential file ď‚— records typically sorted by key 1 01001010 Judy Judy Green Sally Black Tom Blue Judy Green Iris Orange Randy Red File Record Field Byte (ASCII character J) Bit
  • 17. 09/04/1317 VIT - SCSE Files and Streams ď‚—C++ views each file as a sequence of bytes ď‚—File ends with the end-of-file marker ď‚—Stream created when a file is opened ď‚—File processing ď‚—Headers <iostream.h> (cout, cin, cerr, clog) ď‚—and <fstream.h> ď‚—class ifstream - input ď‚—class ofstream - output ď‚—class fstream - either input or output
  • 18. 09/04/1318 VIT - SCSE Creating a Sequential Access File ď‚—Files are opened by creating objects of stream classes ifstream, ofstream or fstream ď‚—File stream member functions for object file: ď‚—file.open(“Filename”, fileOpenMode); ď‚—file.close(); ď‚—destructor automatically closes file if not explicitly closed ď‚—File open modes: Mode Description ios::app Write all output to the end of the file. ios::ate Open a file for output and move to the end of the file (normally used to append data to a file). Data can be written anywhere in the file. ios::in Open a file for input. ios::out Open a file for output. ios::trunc Discard the file’s contents if it exists (this is also the default action for ios::out) ios::binary Open a file for binary (i.e., non-text) input or output. Makes a "line of communication" with the object and the file.
  • 19. 09/04/1319 VIT - SCSE File position pointer <istream> and <ostream> classes provide member functions for repositioning the file pointer (the byte number of the next byte in the file to be read or to be written.) These member functions are: seekg (seek get) for istream class seekp (seek put) for ostream class
  • 20. 09/04/1320 VIT - SCSE Examples of moving a file pointer inClientFile.seekg(0) - repositions the file get pointer to the beginning of the file inClientFile.seekg(n, ios:beg) - repositions the file get pointer to the n-th byte of the file inClientFile.seekg(m, ios:end) -repositions the file get pointer to the m-th byte from the end of file nClientFile.seekg(0, ios:end) - repositions the file get pointer to the end of the file The same operations can be performed with <ostream> function member seekp.
  • 21. 09/04/1321 VIT - SCSE Member functions tellg() and tellp(). Member functions tellg and tellp are provided to return the current locations of the get and put pointers, respectively. long location = inClientFile.tellg(); To move the pointer relative to the current location use ios:cur inClientFile.seekg(n, ios:cur) - moves the file get pointer n bytes forward.
  • 22. 09/04/1322 VIT - SCSE Updating a sequential file Data that is formatted and written to a sequential file cannot be modified easily without the risk of destroying other data in the file. If we want to modify a record of data, the new data may be longer than the old one and it could overwrite parts of the record following it.
  • 23. Problems with sequential files Sequential files are inappropriate for so-called “instant access” applications in which a particular record of information must be located immediately. These applications include banking systems, point-of-sale systems, airline reservation systems, (or any data-base system.) 09/04/1323 VIT - SCSE
  • 24. Random access files Instant access is possible with random access files. Individual records of a random access file can be accessed directly (and quickly) without searching many other records. 09/04/1324 VIT - SCSE
  • 25. Creating a Random Access Fileď‚—write - outputs a fixed number of bytes beginning at a specific location in memory to the specified stream ď‚—When writing an integer number to a file, ď‚—outFile.write( reinterpret_cast<const char *>( &number ), sizeof( number ) ); ď‚—First argument: pointer of type const char * (location to write from) ď‚—address of number cast into a pointer ď‚—Second argument: number of bytes to write(sizeof(number)) ď‚—recall that data is represented internally in binary (thus, integers can be stored in 4 bytes) ď‚—Do not use ď‚—outFile << number; ď‚—could print 1 to 11 digits, each digit taking up a byte of storage 09/04/1325 VIT - SCSE
  • 26. #include <iostream.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" int main() { ofstream outCredit( "credit.dat", ios::ate ); if ( !outCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } cout << "Enter account number " << "(1 to 100, 0 to end input)n? "; clientData client; cin >> client.accountNumber; while ( client.accountNumber > 0 && client.accountNumber <= 100 ) { cout << "Enter lastname, firstname, balancen? "; cin >> client.lastName >> client.firstName >> client.balance; outCredit.seekp( ( client.accountNumber - 1 ) * sizeof( clientData ) ); outCredit.write( reinterpret_cast<const char *>( &client ), sizeof( clientData ) ); cout << "Enter account numbern? "; cin >> client.accountNumber; } return 0; } 09/04/1326 VIT - SCSE
  • 27. Writing Data Randomly to a Random Access File ď‚—seekp can be used in combination with write to store data at exact locations in an output file 09/04/1327 VIT - SCSE
  • 28. Reading data from a random file #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" void outputLine( ostream&, const clientData & ); int main() { ifstream inCredit( "credit.dat", ios::in ); if ( !inCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } cout << setiosflags( ios::left ) << setw( 10 ) << "Account" << setw( 16 ) << "Last Name" << setw( 11 ) << "First Name" << resetiosflags( ios::left ) << setw( 10 ) << "Balance" << endl; clientData client; inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); while ( inCredit && !inCredit.eof() ) { if ( client.accountNumber != 0 ) outputLine( cout, client ); inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); } return 0; } void outputLine( ostream &output, const clientData &c ) { output << setiosflags( ios::left ) << setw( 10 ) << c.accountNumber << setw( 16 ) << c.lastName << setw( 11 ) << c.firstName << setw( 10 ) << setprecision( 2 ) << resetiosflags( ios::left ) << setiosflags( ios::fixed | ios::showpoint ) << c.balance << 'n'; } 09/04/1328 VIT - SCSE
  • 29. The <istream> function read inCredit.read (reinterpret_cast<char *>(&client), sizeof(clientData)); The <istream> function inputs a specified (by sizeof(clientData)) number of bytes from the current position of the specified stream into an object. 09/04/1329 VIT - SCSE