Lecture 12: Classes and Files

22,986 views

Published on

Classes and Files

Published in: Education
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
22,986
On SlideShare
0
From Embeds
0
Number of Embeds
17,395
Actions
Shares
0
Downloads
164
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Lecture 12: Classes and Files

  1. 1. Lecture 12 Classes and FilesTCP1231 Computer Programming I 1
  2. 2. 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 TCP1231 Computer Programming I 2
  3. 3. ClassesTCP1231 Computer Programming I 3
  4. 4. ClassesA class is a logical method to organize data and functions in thesame structure. They are declared using keyword class, whosefunctionality is similar to that of the C++ keyword struct, butwith the possibility of including functions as members, insteadof only data. class class_name { permission_label_1: member1; permission_label_2: member2; ... } object_name; TCP1231 Computer Programming I 4
  5. 5. Classes 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:• 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. TCP1231 Computer Programming I 5
  6. 6. Example 1 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); }; TCP1231 Computer Programming I 6
  7. 7. Example 2 class A declares 3 class A{ variables public: •i is public to all users int i; of class A protected: •j is protected, can int j; only be used by methods in class A or private: its derived classes int k; •k is private, can only }; be used by methods in class A. TCP1231 Computer Programming I 7
  8. 8. 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). Thisclass contains four members: two variables of type int (x and y) in the privatesection (because private is the default permission) and two functions in the publicsection: set_values() and area(), of which we have only included the prototype.Notice the difference between class name and object name: In the previousexample, CRectangle was the class name, whereas rect was an object of typeCRectangle. TCP1231 Computer Programming I 8
  9. 9. #include <iostream> #include <iostream>using namespace std; using namespace std;struct info { class info { public: int id; int id; float avg; float avg; string name; string name;}; };int main () { int main () { info s1; info c1; s1.id=204; c1.id=204; s1.avg=84.8; c1.avg=84.8; s1.name=“qdah"; c1.name=“qdah"; system(“pause”); system(“pause”); return 0; return 0;} } TCP1231 Computer Programming I 9
  10. 10. #include <iostream> #include <iostream>using namespace std; using namespace std;struct info { class info { int id; public: int avg; int id; string name; int avg;}; string name;info read() void read() {{ cin >> id; info data; cin >> avg; cin >> data.id; cin >> name; cin >> data.avg; } cin >> data.name; }; return data; int main () {} info c1;int main () { c1.read(); info s1; s1=read (); return 0; } return 0;} TCP1231 Computer Programming I 10
  11. 11. #include <iostream> #include <iostream>using namespace std; using namespace std;class info { class info { int id; int id; int avg; int avg; string name; string name;public: public: void read() { void read(); cin >> id; }; cin >> avg; void info:: read(){ cin >> name; cin >> id; } cin >> avg;}; cin >> name;int main () { }; info c1; int main () { c1.read(); info c1; c1.read(); return 0;} return 0; } TCP1231 Computer Programming I 11
  12. 12. #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} TCP1231 Computer Programming I 12
  13. 13. #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 area: 12 rect.set_values (3,4); rectb area: 30 rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl;} TCP1231 Computer Programming I 13
  14. 14. Constructors and DestructorsObjects generally need to initialize variables or assign dynamicmemory during their process of creation to become totally operativeand to avoid returning unexpected values during their execution.For example, what would happen if in the previous example wecalled the function area() before having called function set_values?Probably an indetermined result since the members x and y wouldhave never been assigned a value.In order to avoid that, a class can include a special function: aconstructor, which can be declared by naming a member functionwith the same name as the class. This constructor function will becalled 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 aconstructor: TCP1231 Computer Programming I 14
  15. 15. #include <iostream>using namespace std; Example  Constructorclass 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); rect area: 12 CRectangle rectc; rectb area: 30 cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; rectc area: 0 cout << "rectc area: " << rectc.area() << endl;} TCP1231 Computer Programming I 15
  16. 16. #include <iostream>using namespace std; Example class CRectangle { Constructor & Destructors int *width, *height; public: CRectangle (int,int); rect area: 12 ~CRectangle (); rectb area: 30 int area (void) {return (*width * *height);}};CRectangle::CRectangle (int a, int b) { CRectangle::~CRectangle () { width = new int; delete width; height = new int; delete height; *width = a; } *height = b;} int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } TCP1231 Computer Programming I 16
  17. 17. #include <iostream> Point readPoint()#include <math.h> {using namespace std; Point p;struct Point cout<< "enter point x,y : ";{ int x; cin>> p.x >> p.y; int y; return p;}; }void printPoint(Point );float distPoint(Point , Point ); void printPoint(Point p)Point readPoint(); { cout<< "(x = "<< p.x<< ", y = "<<int main(){ p.y<<")"<< endl; Point p1, p2; } float d; p1=readPoint(); cout<< "p1 = "; float distPoint(Point p, Point q) printPoint(p1); { p2=readPoint(); cout<< "p2 = "; float dx = p.x - q.x; printPoint(p2); float dy = p.y - q.y; d= distPoint(p1,p2); float dsquared = dx*dx + dy*dy; cout<< "distance p1 to p2 = "<< d; d= distPoint(p2,p1); return sqrt(dsquared); cout<< "distance p2 to p1 = "<< d; } return 0;} TCP1231 Computer Programming I 17
  18. 18. #include <iostream> int main()#include <math.h> {using namespace std; Point p1, p2;class Point{ float d; private: int x; p1.readPoint(); int y; cout<< "p1 = "; public: p1.printPoint(); void readPoint(); cout<< endl; void printPoint(); p2.readPoint(); float distPoint(Point q); cout<< "p2 = ";}; p2.printPoint();void Point::readPoint(){ cout<< endl; cout<< "enter point x,y : "; cin>> x >> y; d = p1.distPoint(p2);} cout<< "distance p1 to p2 = “ << dvoid Point::printPoint(){ << endl;cout<< "(x = "<< x<< ", y = "<< y <<")"<< endl; } d= p2.distPoint(p1);float Point::distPoint(Point q){ cout<< "distance p2 to p1 = "<< d float dx = x - q.x; << endl<< endl; float dy = y - q.y; float dsquared = dx*dx + dy*dy; system("pause"); return sqrt(dsquared); return 0;} TCP1231 Computer Programming I } 18
  19. 19. FilesTCP1231 Computer Programming I 19
  20. 20. 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 TCP1231 Computer Programming I 20
  21. 21. 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 when your program executes. To use them you only need to #include <iostream> and the appropriate using directives. TCP1231 Computer Programming I 21
  22. 22. 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 TCP1231 Computer Programming I 22
  23. 23. File I/OWhen a program takes input from a file, we say thatit reads from the file.When a program puts data into a file, we say thatit writes to the file.To read or write to a file, we create a stream object,and connect it to the file. TCP1231 Computer Programming I 23
  24. 24. 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 TCP1231 Computer Programming I 24
  25. 25. More on Files  Files 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)  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. 0 1 2 3 4 5 6 7 … n-1 … End-of-file marker TCP1231 Computer Programming I 25
  26. 26. 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"); TCP1231 Computer Programming I 26
  27. 27. 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; TCP1231 Computer Programming I 27
  28. 28. 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; TCP1231 Computer Programming I 28
  29. 29. The fstreams ClassesWe use objects of the ifstream class to read froma 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; TCP1231 Computer Programming I 29
  30. 30. Connecting To a File• Once a stream variable is declared, connect it to a file – Connecting a stream to a file is opening the file – Use the open function of the stream object in_stream.open("infile.dat"); Double quotes Period File name on the disk TCP1231 Computer Programming I 30
  31. 31. 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 fileto 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;OR file.open (“file1.abc", ios::out | ios::app | ios::binary); ofstream file (“file1.abc", ios::out | ios::app | ios::binary); TCP1231 Computer Programming I 31
  32. 32. More processesTo check if the file has been correctly opened we use is_open()that returns a bool type value indicating True in case that indeedthe object has been correctly associated with an open file or Falseotherwise 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 FilesThis for test !“Hi and Bye” îyÑå▌┘┬µα╣ ÜÑå«ìæ Text Files Binary Files TCP1231 Computer Programming I 32
  33. 33. 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 TCP1231 Computer Programming I 33
  34. 34. Example TCP1231 Computer Programming I 34
  35. 35. Text FilesWe use the same members of classes that we used in communicationwith the console (cin and cout). As in the following example, wherewe use the overloaded insertion operator <<#include <fstream> #include <iostream>using namespace std; #include <fstream> using namespace std;int main () { // writing to a text file int main () { // reading a text file ofstream myfile ("file1.txt“, ios::out); char buffer; if (myfile.is_open()) ifstream myfile ("file1.txt“, ios::in); { if (! myfile.is_open()) myfile << “Message from Belal.n"; { cout << "Error"; exit (1); } myfile << “Just Hi and Bye."; myfile.put(‘n’); while (! myfile.eof() ) { myfile.close(); myfile.get (buffer); } cout << buffer; } return 0; return 0;} } eof() TCP1231true if a file opened for reading has reached the end Returns Computer Programming I 35
  36. 36. Text Files Read from a file “in.dat” then Write to a file “out.dat” #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(); } TCP1231 Computer Programming I 36
  37. 37. 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 TCP1231 Computer Programming I 37
  38. 38. 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; TCP1231 Computer Programming I 38
  39. 39. 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 TCP1231 Computer Programming I 39
  40. 40. Binary Files The advantages of binary file are:  No need to convert between the internal representation and a character-based representation  Reduces the associated time to store/retrieve data  Possible conversion and round-off errors are avoided  Storing data objects in binary format usually takes less space (though this depends on the nature of the data) Disadvantages:  The file is not easily readable by humans  Portability becomes an issue, as different operating systems (and even different compilers) may use different internal representations TCP1231 Computer Programming I 40
  41. 41. Creating Binary FilesTo open a file with a stream object we use the function open() void open ( filename, mode | ios::binary); Creating a stream that will handle binary I/O is as simple as setting a flag Create a binary file output stream: ofstream fout (“myFile.txt”, ios::out |ios::trunc | ios::binary); Create a binary file input stream: ifstream fin (“myFile2.txt”, ios::in | ios::binary); TCP1231 Computer Programming I 41
  42. 42. Binary Files (read and write)Two functions are used : READ & WRITEwrite() –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); TCP1231 Computer Programming I 42
  43. 43. Example#include <iostream> ofstream output;#include <fstream> output.open("indata.dat", ios::out|ios::binary);#include <cstring> output.write(reinterpret_cast<char *>(&people),using namespace std; sizeof(person) ); output.close();typedef struct { char gender; person newperson; int age; ifstream input; string name; input.open("indata.dat", ios::in|ios::binary); } person; input.read(reinterpret_cast<char *> (&newperson), sizeof(person) );int main(void) cout << "n Name is ==> " << newperson.name;{ cout << "n Gender is ==> " << newperson.gender; person people; cout << "n Age is ==> " << newperson.age; people.name= "Ali"; input.close(); people.age= 22; people.gender= m; return 0; } TCP1231 Computer Programming I 43
  44. 44. File SeekThe C++ I/O system supports four functions for seeking 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 pointer tellp() ofstream Returns the current position of the put pointer moves the file pointer to the 20th byte in Origin value Seek From … the file, infile. After this, if a read ios::beg seek from beginning of file operation is initiated, the reading starts ios::cur seek from current location from the 21st item within the file. ios::end seek from end of file moves the file pointer to theinfile.seekg(20, ios::beg); or infile.seekg(20); 20th byte in the file outfile. After this, if write operation isoutfile.seekp(20, ios::beg); or outfile.seekp(20); initiated, the writing starts from the 21st item within the file. TCP1231 Computer Programming I 44
  45. 45. SeekSeek call Action performedoutfile.seekg(0, ios::beg) Go to the beginning of the fileoutfile.seekg(0, ios::cur) Stay at the current fileoutfile.seekg(0, ios::end) Go to the end of the fileoutfile.seekg(n, ios::beg) Move to (n+1) byte location in the fileoutfile.seekg(n, ios::cur) Move forward by n bytes from current positionoutfile.seekg(-n, ios::cur) Move backward by n bytes from current positionoutfile.seekg(-n, ios::end) Move forward by n bytes from the endinfile.seekg(n, ios::beg) Move write pointer to (n+1) byte locationinfile.seekg(-n, ios::cur) Move write pointer backward by n bytes TCP1231 Computer Programming I 45
  46. 46. Examples,,, seekp, tellp 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“; 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“; TCP1231 Computer Programming I 46
  47. 47. Examples,,, seekg, tellg ifstream fin(“myFile.txt”); if (fin.is_open()) { char c; fin.seekg(5, ios_base::cur); fin >> c; … } ifstream fin(“myFile.txt”); if (fin.is_open() ) { char c; fin.seekg(fin.tellg()–static_cast<streampos>(5) ); fin >> c; … } TCP1231 Computer Programming I 47
  48. 48. The EndTCP1231 Computer Programming I 48

×