17 files and streams

29
Files and Streams 06/16/22 1 VIT - SCSE By G.SasiKumar., M.E., (Ph.D)., Assistant Professor School of Computing Science and Engineering VIT University

Upload: vit-university

Post on 11-May-2015

920 views

Category:

Technology


2 download

DESCRIPTION

Files and Streams

TRANSCRIPT

Page 1: 17 files and streams

Files and Streams

04/12/231 VIT - SCSE

By

G.SasiKumar., M.E., (Ph.D).,Assistant Professor

School of Computing Science and EngineeringVIT University

Page 2: 17 files and streams

04/12/232 VIT - SCSE

Files

DisketteMemory

Input file

Output file

Used to transfer data to and from disk

Page 3: 17 files and streams

04/12/233 VIT - SCSE

StreamsStream

a channel or medium where data are passed to receivers from senders.

Output Streama channel where data are sent out to a receivercout; the standard output stream (to monitor)the monitor is a destination device

Input Streama channel where data are received from a sendercin; the standard input stream (from the

keyboard)the keyboard is a source device

Page 4: 17 files and streams

04/12/234 VIT - SCSE

Standard Input / Output Streams

Standard Streams use #include <iostream.h>Standard Input Stream

cin names the streamthe extractor operator >> extracts, gets, or receives the

next element from the streamStandard Output Stream

cout names the streamthe inserter operator << inserts, puts, or sends the next

element to the streamOpening & closing of the standard streams occur

automatically when the program begins & ends.

Page 5: 17 files and streams

04/12/235 VIT - SCSE

File Streams

Filesdata structures that are stored separately from

the program (using auxiliary memory)streams must be connected to these filesInput File Stream

extracts, receives, or gets data from the fileOutput 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)

Page 6: 17 files and streams

04/12/236 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>

Page 7: 17 files and streams

04/12/237 VIT - SCSE

Page 8: 17 files and streams

04/12/238 VIT - SCSE

File Handling ClassesHierarchy Diagram

Page 9: 17 files and streams

04/12/239 VIT - SCSE

iosios

streambufstreambuf ostreamostreamistreamistream

iostreamiostream

fstreamfstream

filebuffilebuf

ofstreamofstreamifstreamifstream

fstreambasefstreambase

Page 10: 17 files and streams

04/12/2310 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;

Page 11: 17 files and streams

04/12/2311 VIT - SCSE

Opening Output Files

Ofstream outClientFile(“clients.dat”, ios:out)

OROfstream outClientFile;

outClientFile.open(“clients.dat”, ios:out)

Exampleofstream out(“outf”,ios::out | ios::append);// out is an append connection to outf

Page 12: 17 files and streams

04/12/2312 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 formatios:: in - (input) open a file for inputios::out - (output) open a file for outputios: 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

Page 13: 17 files and streams

04/12/2313 VIT - SCSE

Closing a File

Use close() on object to close connection to file:

ifstream in(“in.dat”);…in.close();

Page 14: 17 files and streams

04/12/2314 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();}

Page 15: 17 files and streams

Using Sequential Access FilesA 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 characterDecimal digits, letters, and special symbols

Field - group of characters conveying meaning Example: your name

Record – group of related fieldsRepresented a struct or a classExample: In a payroll system, a record for a particular

employee that contained his/her identification number, name, address, etc.

File – group of related recordsExample: payroll file

Database – group of related files04/12/2315 VIT - SCSE

Page 16: 17 files and streams

04/12/2316 VIT - SCSE

The Data Hierarchy

Record keyidentifies a record to facilitate the retrieval of specific

records from a fileSequential file

records typically sorted by key

1

01001010

Judy

Judy Green

Sally BlackTom BlueJudy GreenIris OrangeRandy Red

File

Record

Field

Byte (ASCII character J)

Bit

Page 17: 17 files and streams

04/12/2317 VIT - SCSE

Files and Streams

C++ views each file as a sequence of bytesFile ends with the end-of-file marker

Stream created when a file is opened

File processingHeaders <iostream.h> (cout, cin, cerr, clog)and <fstream.h> class ifstream - inputclass ofstream - outputclass fstream - either input or output

Page 18: 17 files and streams

04/12/2318VIT - SCSE

Creating a Sequential Access FileFiles 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 thefile (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 isalso the default action for ios::out)

ios::binary Open a file for binary (i.e., non-text) input oroutput.

Makes a "line of communication" with the object and the file.

Page 19: 17 files and streams

04/12/2319 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 classseekp (seek put) for ostream class

Page 20: 17 files and streams

04/12/2320VIT - 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 fileThe same operations can be performed with

<ostream> function member seekp.

Page 21: 17 files and streams

04/12/2321VIT - 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.

Page 22: 17 files and streams

04/12/2322VIT - 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 belonger than the old one and it could

overwrite parts of the record following it.

Page 23: 17 files and streams

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.)

04/12/2323VIT - SCSE

Page 24: 17 files and streams

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.

04/12/2324VIT - SCSE

Page 25: 17 files and streams

Creating a Random Access Filewrite - outputs a fixed number of bytes beginning

at a specific location in memory to the specified streamWhen 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

04/12/2325VIT - SCSE

Page 26: 17 files and streams

#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, balance\n? "; 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 number\n? "; cin >> client.accountNumber; }

return 0;}

04/12/2326VIT - SCSE

Page 27: 17 files and streams

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

04/12/2327VIT - SCSE

Page 28: 17 files and streams

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';}

04/12/2328VIT - SCSE

Page 29: 17 files and streams

The <istream> function readinCredit.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.

04/12/2329VIT - SCSE