SlideShare une entreprise Scribd logo
1  sur  29
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

Contenu connexe

Tendances (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++
 

Similaire à 17 files and streams

Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Rex 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 exampleSunil 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 referenceanuvayalil5525
 
File management in C++
File management in C++File management in C++
File management in C++apoorvaverma33
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handlingDeepak Singh
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
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 malavRohit 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 SYLLABUSVenugopalavarma 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-filesnoahjamessss
 
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-filescskvsmi44
 

Similaire à 17 files and streams (20)

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
 
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
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
 
cpp-file-handling
cpp-file-handlingcpp-file-handling
cpp-file-handling
 

Plus de Docent Education

Plus de 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
 

Dernier

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

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