EC-241 Object-Oriented Programming

33
EC-241 Object-Oriented Programming LECTURE 12

description

EC-241 Object-Oriented Programming. LECTURE 12. C++ File I /O. A stream is a general name given to a flow of data. Disk file I/O is a special case of the general I/O system The classes used specifically for Disk file I/O are declared in the file FSTREAM. Stream class hierarchy (simplified). - PowerPoint PPT Presentation

Transcript of EC-241 Object-Oriented Programming

Page 1: EC-241 Object-Oriented Programming

EC-241 Object-Oriented Programming

LECTURE 12

Page 2: EC-241 Object-Oriented Programming

C++ File I/O

• A stream is a general name given to a flow of data.

• Disk file I/O is a special case of the general I/O system

• The classes used specifically for Disk file I/O are declared in the file FSTREAM

Page 3: EC-241 Object-Oriented Programming

Stream class hierarchy (simplified)iosios

iosistream

iosostream

iosifstream

iosfstream

iosiostream

iosofstream

Page 4: EC-241 Object-Oriented Programming

Disk File I/O with Streams

• Three relevant classes:– ifstream for input // ifstream in;– ofstream for output // ofstream out;– fstream for both input and output

// fstream io;

Page 5: EC-241 Object-Oriented Programming

Opening and Closing a file• void ifstream::open(const char *filename, ios::openmode mode= ios::in)

• void ofstream::open(const char *filename, ios::openmode mode= ios::out | ios::trunc)

• void fstream::open(const char *filename, ios::openmode mode= ios::in | ios::out)

• ios::in• ios::out• ios::binary• ios::trunc• Ios::app

• Ifstream io(”my file”);

• io.close();

Page 6: EC-241 Object-Oriented Programming

Reading and writing Text Files

• Use << and >> operators the same way you do when performing console I/O, except that instead of using cin, cout substitue a string that is linked to a file

Page 7: EC-241 Object-Oriented Programming

Writing and Reading#include <iostream> # include <fstream>using namespace std;

void main(){

ofstream out("test.txt");

out<<"Computer "<<28.9;out<<"Laptop "<<59.5;

}

#include <iostream> # include <fstream>#include <string>using namespace std; void main(){

string item;float price;

ifstream in("test.txt");

in>>item>>price;

cout<<item<<" "<<price<<endl;in>>item>>price;cout<<item<<" "<<price<<endl;

}

Page 8: EC-241 Object-Oriented Programming

Formatted File I/O

• Numbers are stored as a series of characters• E.g. 6.02 is stored as character ‘6’, followed by

chars ‘.’, ‘0’, and ‘2’.• Inefficient, but easy to implement

Page 9: EC-241 Object-Oriented Programming

Writing (Formatted) Data# include <fstream>#include <string>… void main(){char ch=‘x’; int i=77; double d=6.02;string str1=“Kafka”, str2=“Proust”; //strings without embedded spaces

ofstream outfile(“fdata.txt”);

outfile<<ch <<i <<‘ ‘ //needs space btw numbers <<d <<str1 <<‘ ‘ //needs space btw strings <<str2;

}

Page 10: EC-241 Object-Oriented Programming

Reading (Formatted) Datavoid main(){

char ch; int i; double d;string str1, str2;

ifstream infile(“fdata.txt”);

infile>>ch>>i>>d>>str1>>str2;

cout<<ch<<endl <<i<<endl

<<d<<endl

<<str1<<endl

<<str2<<endl;}

Page 11: EC-241 Object-Oriented Programming

Strings with Embedded Blanks

//file output … void main(){ ofstream outfile(“test.txt”); outfile<<“I fear thee, ancient mariner!\n”; outfile<<“I fear thy skinny hand\n”; outfile<<“And thou art long, and lank, and brown, \n”; outfile<<“As is the ribbed sea sand, \n”;}

Page 12: EC-241 Object-Oriented Programming

Strings with Embedded Blanks//file input… void main(){ const int MAX=100; char buffer[MAX]; ifstream infile(“test.txt”); while (!infile.eof()) // until eof encountered {

infile.getline(buffer, MAX);cout<<buffer<<endl;

}}

Page 13: EC-241 Object-Oriented Programming

Unformatted and Binary I/O

• In binary I/O numbers are stored as they are in the memory rather than as strings of characters

• In binary I/O int is always stored in 4 bytes, whereas its text version might be ”234567”

Page 14: EC-241 Object-Oriented Programming

Unformatted and Binary I/O

• put() and get() can be used to output and input singal characters

• istream &get(char &ch)• ostream &put(char ch)

• read() and write() reads and writes block of binary data

• istream &read(char *buf, streamsize num)• ostream &write(const char *buf, streamsize num)

Page 15: EC-241 Object-Oriented Programming

Unformatted and Binary I/O

const int MAX=100; int buff[MAX]; void main(){

for (int j=0; j<MAX; j++)buff[j]=j;

ofstream os(“edata.dat”, ios::binary);

os.write(reinterpret_cast<char*> (buff), MAX*sizeof(int));

os.close();

Page 16: EC-241 Object-Oriented Programming

Binary I/O for (int j=0; j<MAX; j++)

buff[j]=0; ifstream is(“edata.dat”, ios::binary);

is.read(reinterpret_cast<char*> (buff), MAX*sizeof(int));

for (int j=0; j<MAX; j++)if (buff[j]!=j)cout<<“Data is incorrect\n”;

}

Page 17: EC-241 Object-Oriented Programming

Object I/O//oper.cpp class person {

protected:char name[80];short age;

public:void getData(){

cin>>name;cin>>age;

} };

Page 18: EC-241 Object-Oriented Programming

Object I/O: Writing an object

void main(){

person per;per.getData();ofstream outfile(“PERSON.DAT”, ios::binary);outfile.write(reinterpret_cast<char *> (&per),

sizeof(per));}

Page 19: EC-241 Object-Oriented Programming

Object I/O: Reading an Object//iper.cpp class person {

protected:char name[80];short age;

public:void showData(){

cout<<name;cout<<age;

} };

Page 20: EC-241 Object-Oriented Programming

Object I/O: Reading an object

void main(){

person per;ifstream infile(“PERSON.DAT”, ios::binary);infile.read(reinterpret_cast<char *> (&per),

sizeof(per));per.showData();

}

Page 21: EC-241 Object-Oriented Programming

I/O with Multiple Objects

class person {

protected:char name[80];short age;

public:void getData(){

cin>>name; cin>>age;}void showData(){

cout<<name; cout<<age;}

};

Page 22: EC-241 Object-Oriented Programming

void main() {

char ch; person per;fstream file; //create an i/o filefile.open(“GROUP.DAT”, ios::app|ios::out|ios::in|

ios::binary);do{cout<<“\nEnter person’s data:”;per.getData();file.write(reinterpret_cast<char*>(&per), sizeof(per));cout<<“Enter another person (y/n) ? “;cin>>ch;}while (ch==‘y’);

Page 23: EC-241 Object-Oriented Programming

file.seekg(0); file.read(reinterpret_cast<char*>(&per), sizeof(per)); while (!file.eof()) {

cout<<“\n Person:” ;per.showData();file.read(reinterpret_cast<char*>(&per),

sizeof(per));}}

Page 24: EC-241 Object-Oriented Programming

Accessing Non-Adjacent Locations

• File Position Pointer– Byte number of next byte in the file to be read or

written– For ifstream: get pointer– For ofstream: put pointer

• Functions to position the file position pointer at desired byte:– For ifstream: seekg (seek get)– For ofstream: seekp (seek put)

Page 25: EC-241 Object-Oriented Programming

Examples: Accessing Non-Adjacent Locations

ifstream infile(“data.dat”);

//position to the nth byte of file (n is any int) infile.seekg(n, ios::beg); //offset from beginning (default)

//position n bytes forward from current position infile.seekg(n, ios::cur);

//position n bytes back from end of file infile.seekg(n, ios::end);

//position at end of file infile.seekg(0, ios::end);

Page 26: EC-241 Object-Oriented Programming

Random Access

void main() {

person per; ifstream infile;infile.open(“GROUP.DAT”, ios::in|ios::binary);infile.seekg(0, ios::end); //reach endint endposition=infile.tellg(); int n=endposition/sizeof(person); //total //number

of persons in the filecout<<“There are “<<n<<“persons in the file”;

Page 27: EC-241 Object-Oriented Programming

cout<<“\nEnter person number to read: “; cin>>n; int position= (n-1)*sizeof(person); infile.seekg(position); infile.read(reinterpret_cast<char*> (&per),

sizeof(per)); per.showData(); }

Page 28: EC-241 Object-Oriented Programming

Objects that Read and Write Themselvesclass person {

protected:char name[80];short age;

public:void getData(){ cin>>name>>age; }void showData(){ cout<<name<<age; }void diskIn(int); //read from filevoid diskOut(); //write to filestatic int diskCount(); //return number of persons in file//Note: static functions can be called without any object

};

Page 29: EC-241 Object-Oriented Programming

void person::diskIn(int pn) {

ifstream infile;infile.open(“PERSFILE.DAT”, ios::binary);infile.seekg(pn*sizeof(person));infile.read((char*)this, sizeof(*this));

}

Page 30: EC-241 Object-Oriented Programming

void person::diskOut(){

ofstream outfile;outfile.open(“PERSFILE.DAT”, ios::app|

ios::binary);outfile.write((char*)this, sizeof(*this));

}

Page 31: EC-241 Object-Oriented Programming

int person::diskCount() {

ifstream infile;infile.open(“PERSFILE.DAT”, ios::binary);infile.seekg(0, ios::end);return (int)infile.tellg()/sizeof(person);

}

Page 32: EC-241 Object-Oriented Programming

void main() {

person p; char ch;do{cout<<“\nEnter person’s data:”;p.getData();p.diskOut();cout<<“Enter another person (y/n) ? “;cin>>ch;}while (ch==‘y’);

int n=person::diskCount(); cout<<“There are “<<n<<“persons in the file”;

Page 33: EC-241 Object-Oriented Programming

for (int j=0; j<n; j++) {

cout<<“\n Person “ <<j;p.diskIn(j);p.showData();

}}