1/47 Chapter 10: File IO in OOP with Borland C++.

Презентация:



Advertisements
Похожие презентации
1/27 Chapter 9: Template Functions And Template Classes.
Advertisements

1/30 Chapter 8: Dynamic Binding And Abstract classes.
Unit II Constructor Cont… Destructor Default constructor.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
A class is just a collection of variables--often of different types--combined with a set of related functions. The variables in the class are referred.
Lecture # Computer Architecture Computer Architecture = ISA + MO ISA stands for instruction set architecture is a logical view of computer system.
1/13 Chapter 06- Implementing Operators in a class.
Data Types in C. A Data Type A data type is –A set of values AND –A set of operations on those values A data type is used to –Identify the type of a variable.
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
Standard I/O and Pipes. Standard Input and Output Linux provides three I/O channels to Programs Standard input (STDIN) - keyboard by default Standard.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Applying Route-Maps as BGP Filters.
1 © Luxoft Training 2012 Inner and anonymous classes.
Data Variable and Pointer Variable Pass by Reference Pointer Arithmetic Passing Array Using Pointers Dynamic Allocation.
Basic Input - Output. Output functions printf() – is a library function that displays information on-screen. The statement can display a simple text message.
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
Object Oriented Programming Ashraf Zia Lecturer Abdul Wali Khan University, Mardan. Lecture - 2.
© 2005 Cisco Systems, Inc. All rights reserved.INTRO v Managing Your Network Environment Managing Cisco Devices.
Транксрипт:

1/47 Chapter 10: File IO in OOP with Borland C++

2/47 Review Template function: a way to create a family of related function. Type of parameter in template function will be determined at the place where the function is called. All template datatypes must be present in parameters of template function. Parameters with default value are not applied in template function because the compiler can not determine them at compile-time. A class is called template class if it contains data belongs to a template type.

3/47 Review Syntax for implement a template function template DataType Func(T1 p1, T2 p2) { } Syntax for implementing a method out side the template class declaration template DataType ClassName :: method(params) { } Syntax for using a template class ClassName obj;

4/47 Review: Introduction to streams Stream: a continuous group of data or a channel through which data travels from one point to another. Input stream receives data from a source into a program. Output stream sends data to a destination from the program An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays Variable Data source keyboard String File …… Data source Monitor String File …… Input stream <processing code> output stream <processing code>

5/47 Review: What do streams work? Byte by byte is transferred. Type convert is done automatically At a time, a current position is stored. variable Input data source 12 ab Input stream 12 Convert 12

6/47 Objectives Standard streams String streams File streams

7/ Standard Classes for IO (iostream.h) Review chapter 5 for two classes

8/47 Demo: Input with filtering

9/47 Demo: Input with filtering Nhp c ch ln s nhưng ch ly s

10/ IO with string (strstrea.h) Operators >>, << of the class ios are inherited.

11/47 Methods of string stream Class istrstream Constructors: istrstream::istrstream(const char * S); istrstream::istrstream(const char * S, int n ); Methods:No Class ostrstream Constructors: ostrstream::ostrstream(); // Khi to object vi buffer đng ostrstream::ostrstream(char* S, int n, int=ios::out); Methods: char *pcount(void) : s byte hin hành đang lưu tr d liu. char * str(void) : Đa ch ca buffer ca ostrstream

12/47 String input stream demo

13/47 String output stream demo #include void main() { const buflen=128;// Đ dài ca buffer char buf[buflen];// buffer ca ostrstream int i=100; float x=3.1415; clrscr(); ostrstream S (buf,buflen);// m 1 output string stream S S << "gia tri cua i=" << i // đưa các bin vào string stream S <<" va x=" << x << ends;// đưa tr NULL vào cui chui cout << buf << endl ; // Xut buffer ra màn hình đ kim tra getch(); }

14/ File programming Introdution to File Basic operations on file File Programming with stdio.h (ANSI C) File Programming in OO Read/Write Object From/To File

15/ Introduction to File File: A complete, named collection of information, such as a program, a set of data used by a program, or a user-created document. A file is the basic unit of storage that enables a computer to distinguish one set of information from another. A file is the glue that binds a conglomeration of instructions, numbers, words, or images into a coherent unit that a user can retrieve, change, delete, save, or send to an output device. (MS Computer Dictionary, 5 th Edition)

16/47 Introdution to File Operating System determines a file relying on file name a string Absolute path examples: C:\\TM1\\TM11\\f1.txt or C:/TM1/TM11/f1.txt If the accessed file is put in the current folder, the file is specified using relative path. Relative path examples: employee.dat /data/student.dat

17/47 Introdution to File Two type of Files: Text File: Data in files are stored in ASCII format. Ex: AB and 12 are stored in a file and there is a blank between them: A B 1 2 Binary file: Data in file are stored in binary format of them: A B binary format of 12

18/47 Introdution to File Based on the data formats are used, different functions ared used to access different data. Binary file are used to store fixed-length structures. To access a file, you need to know the strcture of the file and the meanings of every datum. Input files : files having data that can be accessed to variables. Output files: Files allow the values of variables to be written to.

19/ Precedures for File Accessing

20/ File Procesing using stdio.h (ANSI C) File variable declaration: FILE* f ; Opening a file: FILE* f=fopen(filename, mode); mode: r w a r+ w+ rt wt a r+t w+t rb wb r+b w+b return NULL Open file cause an error Closing a file: fclose(f) ; Accessing Text file: VarsReadReturn if EOFWriteReturn if ERROR char cc=fgetc(f)EOF (-1)fputc(c,f)EOF char s[]fgets(s,n,f)NULLfputs(s,f)EOF number xfscanf(f,%&x)EOFfprintf(f, %x)EOF Accessing Binary file: Read structuresfread (&struct, sizeof(struct),n,f )no. of structs Write structuresfwrite (&struct, sizeof(struct),n,f )no. of structs

21/47 int n=5; int a[5] = {8, 7, 2, 0, 9}; Ni dung file s ghi Demo: Function for writing an array of integers with n elements to a text file void WriteFile (int *a, int n, char* fname) { FILE *f = fopen(fname, w); if (!f) { printf(Cannot open the file!); exit(1); } fprintf(f,%d, n); for (int i=0; i<n; ++i) fprintf(f,%d,a[i]); fclose(f); }

22/47 Function for reading a text file to an array of integers with n elements. void ReadFile (char* fname, int *&a, int &n) { FILE *f = fopen(fname, r); if (!f) { printf(Cannot open the file!); exit(1); } fscanf(f,%d, &n); a=new int [n]; for (int i=0; i<n; ++i) fscanf(f,%d,&a[i]); fclose(f); } int n; int a[5]; Ni dung file cn đc Demo:

23/47 Demo: Function for writing an array of emplyees with n elements to a binary file. struct Employee { char Name[51]; int Salary; } ; void WriteFile (Employee* list, int n, char* fname) { FILE *f = fopen(fname, wb); if (!f) { printf(Cannot open the file!); exit(1); } fwrite(list, sizeof(Employee), n, f) ; fclose(f); }

24/47 Demo: Function for reading all content of a binary file to an array of Employees. void ReadFile (char* fname, Employee* &list, int &n) { FILE *f = fopen(fname, rb); if (!f) { printf(Cannot open the file!); exit(1); } fseek(f,SEEK_END, 0) ; // seeking to the end of the file n= int (ftell(f)/sizeof(Employee); // cal. no. of records in file list= new Employee[n]; // allocating memory fseek(f,SEEK_BEG, 0) ; // seeking to the beginning of the file fread(list, sizeof(Employee), n, f) ; // Reading file to array fclose(f); }

25/ File Stream in Borland C++ fstream.h declares file stream classes with the following hierarchy: >>, << are inherited to File objects In File Destructor, codes for closing file are implemented You need not to write codes for them. Data of File objects are file buffers open() close()

26/ File modes:

27/ Class ifstream Constructors ifstream::ifstream(); // declaration only, no open file // open file, mode=input, file buffer is protected ifstream::ifstream(const char* filename, int mode=ios::in, int bufMode= filebuf::openprot); // open file stream with opened file ifstream::ifstream(int fileDescription); // open file stream with opened file and a buffer ifstream::ifstream(int fileDescription, char* buffer, int bufLength);

28/ Class ofstream Constructors ofstream::ofstream(); ofstream::ofstream(const char* filename, int mode=ios::out, int bufMode= filebuf::openprot); ofstream::ofstream(int fileDescription); ofstream::ofstream(int fileDescription, char* buffer, int bufLength);

29/ Manually Openning/Closing a File Use inherited methods from the base class fstreambase void fstreambase :: open ( const char* FileName, int Mode, int = filebuf::openprot ) ; void fstreambase :: close ( ) ; Examples: ofstream f ; f.open (hocsinh.dat); f.close() ; Open file with associating file modes: use OR bit operator Ex: ios::binary|ios::in|ios::out

30/ Some Examples for opening Files Open file f1.txt for reading ifstream f ( f1.txt) ; Open file f2.txt for writing ofstream f ( f2.txt) ; Open file nhanvien.dat for writing at the end of the file: ofstream f ( nhanvien.dat, ios:: out | ios :: binary | ios :: ate ) ;

31/ Reading file to vaiables, Writing variables to File Reading file variables: Use inherited methods from the base class ios and istream: get(), getline(), read (char*, int), gcount(), tellg(), seekg(), ignore(), >>, … Writing variables File: Use inherited methods from the base class ios and ostream: flush(), put(char), write(char*, int), tellp(), seekp(), <<, …

32/ Demo: Print file to the screen

33/47 Demo: copy file byte by byte #include // hàm exit(int) #include // ly khai báo các lp file #include void main (int argNum, char ** args) { if (argNum<3) // Kim tra s lưng đi s khi chy chương trình { cerr << Command format : fcopy1 SrcFile DesFile\n"; exit (0); } ifstream srcF (args[1]); // M file ngun đ đc if ( ! srcF ) { cerr << Cannot open file "<< args[1]; exit(1); } ofstream desF(args[2]); // M file đích đ ghi if ( ! desF ) { cerr << Cannot open file "<< args[2]; exit (1); } char c ; // M đưc c 2 file, đc và ghi tng byte while (srcF.get(c) && desF ) desF.put(c); cout << File copied."; getch(); } Chú ý: Không th chy chương trình bng Ctrl + F9 mà phi thoát v DOS và gõ lnh fcopy1 FileNgun FileĐích

34/ Structures and Binary Files Use read() and write() methods inherited from istream and ostream classes. Read a structure from file istream :: read (char *, int ) Ex: Read structure hs from ifstream f f.read ((char*) &hs, sizeof(hs)); if ( f.gcount()>0) Read successfully Write structure to file ostream :: write (char*, int) Ex: Write structure hs to ofstream f f.write ((char*) &hs, sizeof(hs)); You need to typecast because the first parameters of two methods belong to the char* datatype

35/ File IO with objects Use methods of the istream and ostream classes: read ((char*) &obj, int size) write ((char*) &obj, int size) Writing a structure to file and writing an object to file are the same. If data member of a class are strings, you should declare them as static string with fixed- length.

36/47 Demo: File Person.cpp

37/47 Demo size 3 list Hoa Tan Loan 1580 Person List

38/47 Demo Khi đc/ghi file mt danh sách khi danh sách này đưc cp phát đng, d liu ca danh sách này ch có pointer ch đn mt vùng nh cha d liu thc s, mà ghi d lên file là ghi d liu thc s. Do vy, trong lp thành phn ca danh sách, nên có hành vi ghi đi tưng thành phn này lên file

39/47 Demo

40/47 Demo duplicate

41/ Summary Dòng (stream) là đi tưng cha d liu là mt chui byte làm vic theo cơ ch tun t. Thư vin iostream.h cha khai báo lp ios là lp nn ca các dòng nhp xut, hai lp istream và ostream là các lp dn xut cho tác v nhp xut chun. Toán t >> ca lp istream dùng cho vic nhp d liu cơ bn. Toán t << ca lp ostream dùng cho vic xut d liu cơ bn. Thư vin iomanip.h cha các ch th đnh dng nhp xut d liu. Thư vin fstream.h cha khai báo các lp ifstream và ofstream cho vic thao tác file. Thư vin strstrea.h cha khai báo các lp istrtream và ostrstream cho vic thao tác nhp xut vi chui.

42/47 Exercise Implement classes: –class Product –class SoldProduct –class SoldProductList –class Customer –class Invoice Write a program that will –Accept some invoices then write them to the file invoices.dat –Read all invoices in the file then list them on the screen.

43/47 Hints class Product code name unitAccount price input() output() class SoldProduct soldPrice amount input() output() writeToFile() readFromFile() class SoldProductList maxCount, count **list input() output() writeToFile() readFromFile() class Customer code name address input() output() writeToFile() readFromFile() class InvoiceInfo invoiceNo date input() output() writeToFile() readFromFile() class Invoice input() output() writeToFile() readFromFile() total()

44/47 Subject Summary What is OOP? What is an object in OOP? Advantages of OOP What is encapsulation? What is inheritance? What is polymorphism? Syntax for class declaration in C++ Describe access specifiers: public, private, protected. What is a instance variable? What is a static method of a class?

45/47 Subject Summary What is a friend function of a class? What is a friend class of a class? What is a template function? What is a template class? Distinguish overloading and overriding. What is operator overridding? In C++, How many base classes a class may inherit from? To call explicitly a base mothod, what operator must be used and what syntax is used for it?

46/47 Subject Summary Give an example to depict a calling to base constructor. To obtain polymorphism, what conditions must be satisfied? Give an example to depict template class using. What library must be include to allow File IO with object in C++? What is a stream? What types are streams classified? What type(s) of stream(s) the operators >>, << operate on? To read/write a struct or an object from/to a stream, what methods of IO stream are used?

47/47 Thanks