Upload
horace-gardner
View
231
Download
2
Embed Size (px)
DESCRIPTION
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;
Citation preview
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 functiontemplate <class T1, class T2>DataType Func(T1 p1, T2 p2){}• Syntax for implementing a method out side the template
class declarationtemplate <class T1, class T2>DataType ClassName<T1,T2>:: method(params){}Syntax for using a template classClassName <RealDataType> 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
VariableData source
keyboardStringFile……
Data sourceMonitorStringFile……
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.
variableInput data source
‘1’ ‘2’ ‘ ‘ ‘a’ ‘b’
Input stream
‘1’ ‘2’ ‘ ‘ Convert
1212
6/47
Objectives
• Standard streams• String streams• File streams
7/47
10.1-Standard Classes for IO (iostream.h)
Review chapter 5for two classes
8/47
Demo: Input with filtering
9/47
Demo: Input with filtering
Nhập cả chữ lẫn số nhưng chỉ lấy
số
10/47
10.2- 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(); // Khởi tạo object với buffer động ostrstream::ostrstream(char* S , int n , int=ios::out); Methods: char *pcount(void) : số byte hiện hành đang lưu trữ dữ liệu . char * str(void) : Địa chỉ của buffer của ostrstream
12/47
String input stream demo
13/47
String output stream demo
#include <strstrea.h>#include <conio.h>void main(){ const buflen=128; // Độ dài của buffer char buf[buflen]; // buffer của 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 biến vào string stream
S <<" va x=" << x << ends; // đưa trị NULL vào cuối chuỗi cout << buf << endl ; // Xuất buffer ra màn hình để kiểm tra getch();}
14/47
10.3- 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/47
10.3.1- 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, 5th Edition)
16/47
Introdution to File
Operating System determines a file relying on file name a stringAbsolute 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:
0100000101000010001000000011000100110010 ‘A’ ‘B’ ‘ ‘ ‘1’ ‘2’
Binary file: Data in file are stored in binary format of them:
01000001010000100000000000001100 ‘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/47
10.3.2- Precedures for File Accessing
20/47
10.3.3- 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:
Vars Read Return if EOF Write Returnif ERROR
char c c=fgetc(f) EOF (-1) fputc(c,f) EOFchar s[] fgets(s,n,f) NULL fputs(s,f) EOF
number x fscanf(f,”%♣”&x) EOF fprintf(f, ”%♣”x) EOF
Accessing Binary file:
Read structures fread (&struct, sizeof(struct),n,f ) no. of structsWrite structures fwrite (&struct, sizeof(struct),n,f ) no. of structs
21/47
int n=5; int a[5] = {8, 7, 2, 0, 9};
5 8 7 2 0 9
Nội 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];
5 8 7 2 0 9
Nội dung file cần đọ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/47
10.4- 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/47
10.5-File modes:
27/47
10.6- Class ifstream Constructors
ifstream::ifstream(); // declaration only, no open file// open file, mode=input, file buffer is protectedifstream::ifstream(const char* filename, int mode=ios::in, int bufMode= filebuf::openprot);// open file stream with opened fileifstream::ifstream(int fileDescription);// open file stream with opened file and a bufferifstream::ifstream(int fileDescription, char* buffer, int bufLength);
28/47
10.7-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/47
10.8-Manually Openning/Closing a File
Use inherited methods from the base class fstreambasevoid fstreambase :: open ( const char* FileName, int Mode, int = filebuf::openprot ) ;void fstreambase :: close ( ) ;Examples:ofstream f ;f.open (“hocsinh.dat”);< others operations>f.close() ;Open file with associating file modes: use OR bit operator
Ex: ios::binary|ios::in|ios::out
30/47
10.9-Some Examples for opening Files
Open file “f1.txt” for reading ifstream f ( “f1.txt”) ;
Open file “f2.txt” for writingofstream 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/47
10.10-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/47
10.11- Demo: Print file to the screen
33/47
Demo: copy file byte by byte#include <stdlib.h> // hàm exit(int)#include <fstream.h> // lấy khai báo các lớp file #include <conio.h>void main (int argNum , char ** args){ if (argNum<3) // Kiểm tra số lượng đối số khi chạy chương trình { cerr << “Command format : fcopy1 SrcFile DesFile\n"; exit (0); } ifstream srcF (args[1]); // Mở file nguồn để đọ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 từng byte while (srcF.get(c) && desF ) desF.put(c); cout << “File copied."; getch();}
Chú ý: Không thể chạy chương trình bằng Ctrl + F9 mà phải thoát về DOS và gõ lệnh fcopy1 FileNguồn FileĐích
34/47
10.12-Structures and Binary FilesUse 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/47
10.13- 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 3list 1230
1510123015401580
21Hoa1510
24Tan1540
23Loan1580
PersonList
38/47
DemoKhi đọc/ghi file một danh sáchkhi danh sách này được cấpphát động, dữ liệu của danhsách này chỉ có pointer chỉđến một vùng nhớ chứa dữliệu thực sự, mà ghi dữ lên file là ghi dữ liệu thực sự.Do vậy, trong lớp thành phầncủa danh sách, nên có hành vighi đối tượng thành phần nàylên file
39/47
Demo
40/47
Demo
duplicate
41/47
10.14- Summary
Dòng (stream) là đối tượng chứa dữ liệu là một chuỗi byte làm việc theo cơ chế tuần tự.Thư viện iostream.h chứa khai báo lớp ios là lớp nền của các dòng nhạp xuất, hai lớp istream và ostream là các lớp dẫn xuất cho tác vụ nhập xuất chuẩn.Toán tử >> của lớp istream dùng cho việc nhập dữ liệu cơ bản.Toán tử << của lớp ostream dùng cho việc xuất dữ liệu cơ bản.Thư viện iomanip.h chứa các chỉ thị định dạng nhập xuất dữ liệu.Thư viện fstream.h chứa khai báo các lớp ifstream và ofstream cho việc thao tác file.Thư viện strstrea.h chứa khai báo các lớp istrtream và ostrstream cho việc thao tác nhập xuất với chuỗi.
42/47
Exercise• Implement classes:
– class Product <code,name,unit_account,price>– class SoldProduct <code,name,unit_account,sold
price,amount>– class SoldProductList <maxCount,count,sold
Products>– class Customer<code,name,address>– class Invoice <invoice number,
date,customer,sold product list> • 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
Hintsclass ProductcodenameunitAccountpriceinput()output()
class SoldProduct soldPriceamountinput()output()writeToFile()readFromFile()
class SoldProductList maxCount, count**listinput()output()writeToFile()readFromFile()
class Customercodenameaddressinput()output()writeToFile()readFromFile()
class InvoiceInfoinvoiceNodateinput()output()writeToFile()readFromFile()
class Invoiceinput()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