+ All Categories
Home > Education > Lecture 12: Classes and Files

Lecture 12: Classes and Files

Date post: 11-May-2015
Category:
Upload: dr-md-shohel-sayeed
View: 8,154 times
Download: 2 times
Share this document with a friend
Description:
Classes and Files
Popular Tags:
48
1 TCP1231 Computer Programming I Lecture 12 Classes and Files
Transcript
Page 1: Lecture 12: Classes and Files

1TCP1231 Computer Programming I

Lecture 12Classes and

Files

Page 2: Lecture 12: Classes and Files

2TCP1231 Computer Programming I

Objectives

To learn about classes and files

Explore how to declare and manipulate classes.

To illustrate the usage of classes with arrays, structure, and functions.

To learn how to use text and binary files

Page 3: Lecture 12: Classes and Files

3TCP1231 Computer Programming I

Classes

Page 4: Lecture 12: Classes and Files

4TCP1231 Computer Programming I

ClassesA class is a logical method to organize data and functions in the same structure. They are declared using keyword class, whose functionality is similar to that of the C++ keyword struct, but with the possibility of including functions as members, instead of only data.

class class_name {

permission_label_1: member1;

permission_label_2: member2;

... } object_name;

Page 5: Lecture 12: Classes and Files

5TCP1231 Computer Programming I

where class_name is a name for the class (user defined type) and the optional field object_name is one, or several, valid object identifiers. The body of the declaration can contain members, that can be either data or function declarations, and optionally permission labels, that can be any of these three keywords: private:, public: or protected:. They make reference to the permission which the following members acquire:

Classes

• private members of a class are accessible only from other members of their same class or from their "friend" classes.

• protected members are accessible from members of their same class and friend classes, and also from members of their derived classes.

• public members are accessible from anywhere the class is visible.

Page 6: Lecture 12: Classes and Files

6TCP1231 Computer Programming I

class student{int a;char b;int f1(int );

private: int c;

float d;void f2(int, int);

protected:int e;string addr;float f3(float, char);

public:int g;string name;void f4(int, int, string);int f5(int, float, char);

};

Example 1

Page 7: Lecture 12: Classes and Files

7TCP1231 Computer Programming I

class A{public: int i;protected: int j;private: int k;

};

Example 2class A declares 3 variables

•i is public to all users of class A

•j is protected, can only be used by methods in class A or its derived classes

•k is private, can only be used by methods in class A.

Page 8: Lecture 12: Classes and Files

8TCP1231 Computer Programming I

Classes

If we declare members of a class before including any permission label, the members are considered private, since it is the default permission that the members of a class declared with the class keyword acquire

class CRectangle {

int x, y; public:

void set_values (int,int); int area (void);

} rect;

Declares class CRectangle and an object called rect of this class (type). This class contains four members: two variables of type int (x and y) in the private section (because private is the default permission) and two functions in the public section: set_values() and area(), of which we have only included the prototype.

Notice the difference between class name and object name: In the previous example, CRectangle was the class name, whereas rect was an object of type CRectangle.

Page 9: Lecture 12: Classes and Files

9TCP1231 Computer Programming I

#include <iostream>using namespace std;

class info { public: int id; float avg; string name;};

int main () { info c1; c1.id=204; c1.avg=84.8; c1.name=“qdah";

system(“pause”); return 0;}

#include <iostream>using namespace std;

struct info {

int id; float avg; string name;};

int main () { info s1; s1.id=204; s1.avg=84.8; s1.name=“qdah";

system(“pause”); return 0;}

Page 10: Lecture 12: Classes and Files

10TCP1231 Computer Programming I

#include <iostream>using namespace std;

class info {public: int id; int avg; string name; void read() { cin >> id; cin >> avg; cin >> name; } };int main () { info c1; c1.read(); return 0;}

#include <iostream>using namespace std;

struct info { int id; int avg; string name;};info read(){

info data; cin >> data.id; cin >> data.avg; cin >> data.name; return data;}int main () { info s1; s1=read (); return 0;}

Page 11: Lecture 12: Classes and Files

11TCP1231 Computer Programming I

#include <iostream>using namespace std;

class info { int id; int avg; string name;public: void read(); };void info:: read(){ cin >> id; cin >> avg; cin >> name;}; int main () { info c1; c1.read(); return 0;}

#include <iostream>using namespace std;

class info { int id; int avg; string name;public: void read() { cin >> id; cin >> avg; cin >> name; } };int main () { info c1; c1.read(); return 0;}

Page 12: Lecture 12: Classes and Files

12TCP1231 Computer Programming I

#include <iostream>using namespace std;

class CRectangle { int x, y; public: void set_values (int,int); int area (void) {return (x*y);}};void CRectangle::set_values (int a, int b) { x = a; y = b;}

int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0;}

area: 12

Page 13: Lecture 12: Classes and Files

13TCP1231 Computer Programming I

#include <iostream>using namespace std;

class CRectangle { int x, y; public: void set_values (int,int); int area (void) {return (x*y);}};void CRectangle::set_values (int a, int b) { x = a; y = b;}

int main () { CRectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() <<

endl;}

rect area: 12rectb area: 30

Page 14: Lecture 12: Classes and Files

14TCP1231 Computer Programming I

Constructors and DestructorsObjects generally need to initialize variables or assign dynamic memory during their process of creation to become totally operative and to avoid returning unexpected values during their execution. For example, what would happen if in the previous example we called the function area() before having called function set_values? Probably an indetermined result since the members x and y would have never been assigned a value.

In order to avoid that, a class can include a special function: a constructor, which can be declared by naming a member function with the same name as the class. This constructor function will be called automatically when a new instance of the class is created (when declaring a new object or allocating an object of that class) and only then. We are going to implement CRectangle including a constructor:

Page 15: Lecture 12: Classes and Files

15TCP1231 Computer Programming I

#include <iostream>using namespace std;

class CRectangle { int width, height; public: CRectangle () { width = 0; height = 0;}; CRectangle (int,int); int area (void) {return (width*height);}};CRectangle::CRectangle (int a, int b) { width = a; height = b;}

int main () { CRectangle rect (3,4); CRectangle rectb (5,6); CRectangle rectc; cout << "rect area: " << rect.area() <<

endl; cout << "rectb area: " << rectb.area()

<< endl; cout << "rectc area: " << rectc.area()

<< endl;}

rect area: 12rectb area: 30rectc area: 0

Example Constructor

Page 16: Lecture 12: Classes and Files

16TCP1231 Computer Programming I

#include <iostream>using namespace std;

class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area (void) {return (*width *

*height);}};

CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b;}

rect area: 12rectb area: 30

CRectangle::~CRectangle () { delete width; delete height;}

int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area()

<< endl; cout << "rectb area: " <<

rectb.area() << endl; return 0;}

Example

Constructor & Destructors

Page 17: Lecture 12: Classes and Files

17TCP1231 Computer Programming I

#include <iostream>#include <math.h>using namespace std;

struct Point{ int x; int y; };void printPoint(Point );float distPoint(Point , Point );Point readPoint();

int main(){ Point p1, p2; float d; p1=readPoint(); cout<< "p1 =

"; printPoint(p1); p2=readPoint(); cout<< "p2 =

"; printPoint(p2); d= distPoint(p1,p2); cout<< "distance p1 to p2 = "<<

d; d= distPoint(p2,p1); cout<< "distance p2 to p1 = "<<

d; return 0;}

Point readPoint(){ Point p;

cout<< "enter point x,y : "; cin>> p.x >> p.y; return p;}

void printPoint(Point p){ cout<< "(x = "<< p.x<< ", y =

"<< p.y<<")"<< endl;}

float distPoint(Point p, Point q){ float dx = p.x - q.x; float dy = p.y - q.y; float dsquared = dx*dx + dy*dy; return sqrt(dsquared);}

Page 18: Lecture 12: Classes and Files

18TCP1231 Computer Programming I

#include <iostream>#include <math.h>using namespace std;class Point{ private: int x; int y; public: void readPoint(); void printPoint(); float distPoint(Point q); };void Point::readPoint(){ cout<< "enter point x,y : "; cin>> x >> y;}void Point::printPoint(){ cout<< "(x = "<< x<< ", y = "<< y

<<")"<< endl; }float Point::distPoint(Point q){ float dx = x - q.x; float dy = y - q.y; float dsquared = dx*dx + dy*dy; return sqrt(dsquared);}

int main(){ Point p1, p2; float d;

p1.readPoint(); cout<< "p1 = "; p1.printPoint(); cout<< endl; p2.readPoint(); cout<< "p2 = "; p2.printPoint(); cout<< endl; d = p1.distPoint(p2); cout<< "distance p1 to p2 =

“ << d << endl;

d= p2.distPoint(p1); cout<< "distance p2 to p1 =

"<< d << endl<< endl;

system("pause"); return 0;}

Page 19: Lecture 12: Classes and Files

19TCP1231 Computer Programming I

Files

Page 20: Lecture 12: Classes and Files

20TCP1231 Computer Programming I

Streams and Basic File I/O• Files for I/O are the same type of files used to

store programs

• A stream is a flow of data.– Input stream: Data flows into the program

• If input stream flows from keyboard, the program will accept data from the keyboard• If input stream flows from a file, the program will accept data from the file

– Output stream: Data flows out of the program• To the screen• To a file

Page 21: Lecture 12: Classes and Files

21TCP1231 Computer Programming I

Standard I/O

•cin – the standard input stream

•cout – the standard output stream

•cerr – the standard error stream

These streams are automatically created for you whenyour program executes. To use them you only need to#include <iostream> and the appropriate using directives.

Page 22: Lecture 12: Classes and Files

22TCP1231 Computer Programming I

Why use Files?

• Files allow you to store data permanently!• Data output to a file lasts after the program ends• An input file can be used over and over

– No typing of data again and again for testing• Create a data file or read an output file at your

convenience• Files allow you to deal with larger data sets

Page 23: Lecture 12: Classes and Files

23TCP1231 Computer Programming I

File I/O

When a program takes input from a file, we say thatit reads from the file.

When a program puts data into a file, we say that it writes to the file.

To read or write to a file, we create a stream object, and connect it to the file.

Page 24: Lecture 12: Classes and Files

24TCP1231 Computer Programming I

File I/O• Reading from a file

– Taking input from a file– Done from beginning to the end

• No backing up to read something again • Just as done from the keyboard

• Writing to a file– Sending output to a file– Done from beginning to end

• No backing up to write something again• Just as done to the screen

Page 25: Lecture 12: Classes and Files

25TCP1231 Computer Programming I

More on FilesFiles are used for permanent storage of data.Files are stored on secondary storage devices such as

magnetic disks, optical disks and tapes.Bit: smallest data items in a computer ( 0 or 1)

Byte: Sequence of Bits (8 Bits)

0 1 2 3 4 5 6 7 … n-1

End-of-file marker

……

C++ views each file simple 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.

Page 26: Lecture 12: Classes and Files

26TCP1231 Computer Programming I

Input/Output with files

C++ has support both for input and output with files through the following classes:

ifstream: File class for reading operations (derived from istream)

ofstream: File class for writing operations (derived from ostream)

fstream: File class for both reading and writing operations (derived from iostream)

#include <fstream>using namespace std;

int main(){ ofstream outfile("myfile1.dat"); ifstream infile ("myfile2.dat"); fstream iofile ("myfile3.dat");

Page 27: Lecture 12: Classes and Files

27TCP1231 Computer Programming I

Input-file Stream (ifstream)

• Input-file streams are of type ifstream

• Type ifstream is defined in the fstream library– You must use the include and using directives

#include <fstream> using namespace std;

• Declare an input-file stream variable using ifstream in_stream;

Page 28: Lecture 12: Classes and Files

28TCP1231 Computer Programming I

Output-file Stream (ofstream)

• Output-file streams of are type ofstream

• Type ofstream is defined in the fstream library– You must use these include and using directives

#include <fstream> using namespace std;

• Declare an input-file stream variable using ofstream out_stream;

Page 29: Lecture 12: Classes and Files

29TCP1231 Computer Programming I

The fstreams Classes

We use objects of the ifstream class to read from a file, and objects of the ofstream class to write toa file.

These classes are defined in <fstream>. To use themwe must write

#include <fstream>using std::ifstream;using std::ofstream;

Page 30: Lecture 12: Classes and Files

30TCP1231 Computer Programming I

Connecting To a File

• Once a stream variable is declared, connect it toa file– Connecting a stream to a file is opening the file– Use the open function of the stream object

in_stream.open("infile.dat");

Period

File name on the disk

Double quotes

Page 31: Lecture 12: Classes and Files

31TCP1231 Computer Programming I

How to open files?To open a file with a stream object we use the function open()

void open ( filename, mode);

filename is a string of characters representing the name of the file to be opened and mode is a combination of the following flags:

ios::in Open file for reading

ios::out Open file for writing

ios::ate Initial position: end of file

ios::app Every output is appended at the end of file

ios::trunc If the file already existed it is erased

ios::binary Binary mode

ofstream file; file.open (“file1.abc", ios::out | ios::app | ios::binary);

ofstream file (“file1.abc", ios::out | ios::app | ios::binary);

OR

Page 32: Lecture 12: Classes and Files

32TCP1231 Computer Programming I

To check if the file has been correctly opened we use is_open() that returns a bool type value indicating True in case that indeed the object has been correctly associated with an open file or False otherwise

After we finish using the file we must close it, to do that the function close() is used.After we call close(), the stream object can be used to open another file, and the file is available again to be opened by other processes

Files

Text Files Binary Files

This for test“Hi and Bye”

!îyÑå▌┘┬µα╣

ÜÑå«ìæ

More processes

Page 33: Lecture 12: Classes and Files

33TCP1231 Computer Programming I

Closing A File

• After using a file, it should be closed– This disconnects the stream from the file– Close files to reduce the chance of a file being

corrupted if the program terminates abnormally

• It is important to close an output file if your program later needs to read input from the output file

• The system will automatically close files if you forget as long as your program ends normally

Page 34: Lecture 12: Classes and Files

34TCP1231 Computer Programming I

Example

Page 35: Lecture 12: Classes and Files

35TCP1231 Computer Programming I

Text FilesWe use the same members of classes that we used in communication with the console (cin and cout). As in the following example, where we use the overloaded insertion operator <<

#include <fstream>using namespace std;

int main () { // writing to a text file ofstream myfile ("file1.txt“, ios::out); if (myfile.is_open()) { myfile << “Message from Belal.\n"; myfile << “Just Hi and Bye."; myfile.put(‘\n’); myfile.close(); }

return 0;}

#include <iostream>#include <fstream>using namespace std;int main () { // reading a text file char buffer; ifstream myfile ("file1.txt“, ios::in); if (! myfile.is_open()) { cout << "Error"; exit (1); }

while (! myfile.eof() ) { myfile.get (buffer); cout << buffer; } return 0;}

eof() Returns true if a file opened for reading has reached the end

Page 36: Lecture 12: Classes and Files

36TCP1231 Computer Programming I

Text Files

#include <fstream>#include <iostream>using namespace std; int main(){ char ch;

ifstream infile("IN.DAT");ofstream outfile("OUT.DAT");while (infile)

{infile.get(ch);outfile.put(ch);

} infile.close();}

Read from a file “in.dat” then Write to a file “out.dat”

Page 37: Lecture 12: Classes and Files

37TCP1231 Computer Programming I

The End of The File

• Input files used by a program may vary in length– Programs may not be able to assume the number

of items in the file

• A way to know the end of the file is reached:– The boolean expression (in_stream >> next)

• Reads a value from in_stream and stores it in next• True if a value can be read and stored in next• False if there is not a value to be read

Page 38: Lecture 12: Classes and Files

38TCP1231 Computer Programming I

End of The File - Example

• To calculate the average of the numbers in a file– double next, sum = 0;

int count = 0; while(in_stream >> next) {

sum = sum + next; count++; }

double average = sum / count;

Page 39: Lecture 12: Classes and Files

39TCP1231 Computer Programming I

Binary Files

When we introduced C++ I/O, we said that input and output streams converted between the programs internal representation for data objects and characters (such as from the internal representation for the number 15 to the characters ‘1’ and ‘5’ and vice versa)

Reason for doing this:

To translate between the internal binary representation and a format that is easier to understand for humans.

Thus, C++ allows us to perform binary file I/O, in which we store and retrieve the original binary representation for data objects

Page 40: Lecture 12: Classes and Files

40TCP1231 Computer Programming I

Binary Files

The advantages of binary file are:No need to convert between the internal representation and

a character-based representationReduces the associated time to store/retrieve dataPossible conversion and round-off errors are avoidedStoring data objects in binary format usually takes less

space (though this depends on the nature of the data)

Disadvantages:Disadvantages:The file is not easily readable by humansPortability becomes an issue, as different operating

systems (and even different compilers) may use different internal representations

Page 41: Lecture 12: Classes and Files

41TCP1231 Computer Programming I

To open a file with a stream object we use the function open()

void open ( filename, mode | ios::binary);

Creating Binary Files

Creating a stream that will handle binary I/O is as simple as setting a flagCreate a binary file output stream:

Create a binary file input stream:

ofstream fout (“myFile.txt”, ios::out |ios::trunc | ios::binary);

ifstream fin (“myFile2.txt”, ios::in | ios::binary);

Page 42: Lecture 12: Classes and Files

42TCP1231 Computer Programming I

Two functions are used : READ & WRITE

write()

–Lets us write a specified number of characters to an output stream

–does a straight byte-by-byte copy

fout.write(reinterpret_cast<char *>(&obj), sizeof obj);

read ( )

–Lets us read a specified number of characters to an output stream

–does a straight byte-by-byte read

fin.read(reinterpret_cast<char *>(&obj), sizeof obj);

Binary Files (read and write)

Page 43: Lecture 12: Classes and Files

43TCP1231 Computer Programming I

#include <iostream>#include <fstream>#include <cstring>using namespace std;

typedef struct { char gender; int age; string name; } person;

int main(void){ person people; people.name= "Ali"; people.age= 22; people.gender= 'm';

Example ofstream output; output.open("indata.dat", ios::out|ios::binary); output.write(reinterpret_cast<char *>(&people),

sizeof(person) ); output.close(); person newperson; ifstream input; input.open("indata.dat", ios::in|ios::binary); input.read(reinterpret_cast<char *> (&newperson),

sizeof(person) ); cout << "\n Name is ==> " << newperson.name; cout << "\n Gender is ==> " << newperson.gender; cout << "\n Age is ==> " << newperson.age; input.close();

return 0; }

Page 44: Lecture 12: Classes and Files

44TCP1231 Computer Programming I

seekg() ifstream Moves get file pointer to a specific location seekp() ofstream Moves put file pointer to a specific location tellg() ifstream Returns the current position of the get pointertellp() ofstream Returns the current position of the put pointer

The C++ I/O system supports four functions for seeking

File Seek

Origin value Seek From … ios::beg seek from beginning of file ios::cur seek from current location ios::end seek from end of file

infile.seekg(20, ios::beg); or infile.seekg(20);

outfile.seekp(20, ios::beg); or outfile.seekp(20);

moves the file pointer to the 20th byte in the file, infile. After this, if a read operation is initiated, the reading starts from the 21st item within the file.

moves the file pointer to the 20th byte in the file outfile. After this, if write operation is initiated, the writing starts from the 21st item within the file.

Page 45: Lecture 12: Classes and Files

45TCP1231 Computer Programming I

Seek call Action performed

outfile.seekg(0, ios::beg) Go to the beginning of the file

outfile.seekg(0, ios::cur) Stay at the current file

outfile.seekg(0, ios::end) Go to the end of the file

outfile.seekg(n, ios::beg) Move to (n+1) byte location in the file

outfile.seekg(n, ios::cur) Move forward by n bytes from current position

outfile.seekg(-n, ios::cur) Move backward by n bytes from current position

outfile.seekg(-n, ios::end) Move forward by n bytes from the end

infile.seekg(n, ios::beg) Move write pointer to (n+1) byte location

infile.seekg(-n, ios::cur) Move write pointer backward by n bytes

Seek

Page 46: Lecture 12: Classes and Files

46TCP1231 Computer Programming I

ofstream fout(“myFile.txt”);if (fout.is_open()) { fout << “Hello, this is a file.” << endl; fout.seekp(15); fout << “not a file“;

ofstream fout(“myFile.txt”);if (fout.is_open() ) { fout << “Hello,this is a file.” << endl; fout.seekp(fout.tellp()– static_cast<streampos>(8)); fout << “not a file“;

Examples,,, seekp, tellp

ofstream fout(“myFile.txt”);if (fout.is_open()) { fout << “Hello, this is a file.” << endl; fout.seekp(-8, ios_base::cur); fout << “not a file“;

Page 47: Lecture 12: Classes and Files

47TCP1231 Computer Programming I

ifstream fin(“myFile.txt”);if (fin.is_open() ) { char c; fin.seekg(fin.tellg()–static_cast<streampos>(5) ); fin >> c;… }

Examples,,, seekg, tellg

ifstream fin(“myFile.txt”);if (fin.is_open()) { char c; fin.seekg(5, ios_base::cur); fin >> c;… }

Page 48: Lecture 12: Classes and Files

48TCP1231 Computer Programming I

The End


Recommended