611 18200 計算機程式語言 Lecture 17-1 國立台灣大學生物機電系 林達德 17 File Processing.

Slides:



Advertisements
Similar presentations
1 Classes and Data Abstraction and File Processing Lecture 13.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - File Processing Outline 14.1 Introduction 14.2 The Data Hierarchy 14.3 Files and Streams.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
CPSC 231 D.H. C++ File Processing 1 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random access files.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 2006 Pearson Education, Inc. All rights reserved File Processing.
計算機概論實習 Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker n-1 end-of-file marker 67 This is.
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
Lec11: File Processing 廖雪花 TEL: 年 5 月.
 2006 Pearson Education, Inc. All rights reserved File Processing.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
1 File I/O In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
計算機程式語言 Lecture 8-1 國立臺灣大學生物機電系 8 8 I/O File Streams and Data Files.
COIT29222-Structured Programming Lecture Week 12  Reading: Textbook (4 th Ed.), Chapter 14 Textbook (6 th Ed.), Chapter 17 Study Guide Book 3, Module.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 14 – File Processing Outline 14.1Introduction 14.2The Data Hierarchy 14.3Files and Streams.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Programming Practice Introduction Tree Operations. Binary Search Tree. File Processing Create, read, write and update files. Sequential.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005.
 2008 Pearson Education, Inc. All rights reserved File Processing.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - File Processing Outline 14.1 Introduction 14.2 The Data Hierarchy 14.3 Files and Streams.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
File I/O. fstream files File: similar to vector of elements Used for input and output Elements of file can be –character (text)struct –object (non-text.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
DCT1063 Programming 2 CHAPTER 3 FILE INPUT AND FILE OUTPUT Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
計算機程式語言 Lecture 02-1 國立台灣大學生物機電系 林達德 2 2 Introduction to C++ Programming.
計算機程式語言 Lecture 03-1 國立台灣大學生物機電系 林達德 3 3 Introduction to Classes and Objects.
1 CSC241: Object Oriented Programming Lecture No 32.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 29 Thanks for Lecture Slides:
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
1 Today’s Objectives  Announcements Homework #5 is due next Monday, July 24. Since this date is so close to the end of the semester, no late assignments.
Learners Support Publications Working with Files.
Binary Files. Text Files vs. Binary Files Text files: A way to store data in a secondary storage device using Text representation (e.g., ASCII characters)
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني I/O and File management(cont.) Binary and random files.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
CS212: Object Oriented Analysis and Design
File Processing.
File Processing.
11 C File Processing.
17 File Processing.
TMF1414 Introduction to Programming
CPSC 231 D.H. C++ File Processing
17 File Processing.
Chapter 14 – File Processing
Chapter 11 – File Processing
MSIS 670: Object-Oriented Software Engineering
17 File Processing.
files Dr. Bhargavi Goswami Department of Computer Science
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Fundamental of Programming (C)
C++ Programming Lecture 8 File Processing
Presentation transcript:

計算機程式語言 Lecture 17-1 國立台灣大學生物機電系 林達德 17 File Processing

計算機程式語言 Lecture 17-2 國立台灣大學生物機電系 林達德 17.1 Introduction 17.2 The Data Hierarchy 17.3 Files and Streams 17.4 Creating a Sequential File 17.5 Reading Data from a Sequential File 17.6 Updating Sequential Files 17.7 Random-Access Files 17.8 Creating a Random-Access File 17.9 Writing Data Randomly to a Random-Access File Reading from a Random-Access File Sequentially Case Study: A Transaction-Processing Program Input/Output of Objects

計算機程式語言 Lecture 17-3 國立台灣大學生物機電系 林達德 OBJECTIVES In this chapter you will learn: To create, read, write and update files. Sequential file processing. Random-access file processing. To use high-performance unformatted I/O operations. The differences between formatted-data and raw-data file processing. To build a transaction-processing program using random-access file processing.

計算機程式語言 Lecture 17-4 國立台灣大學生物機電系 林達德 17.1 Introduction Storage of data –Arrays, variables are temporary –Files are permanent Magnetic disk, optical disk, tapes In this chapter –Create, update, process files –Sequential and random access –Formatted and raw processing

計算機程式語言 Lecture 17-5 國立台灣大學生物機電系 林達德 17.2 The Data Hierarchy From smallest to largest –Bit (binary digit) 1 or 0 Everything in computer ultimately represented as bits Cumbersome for humans to use Character set –Digits, letters, symbols used to represent data –Every character represented by 1's and 0's –Byte: 8 bits Can store a character ( char ) Also Unicode for large character sets ( wchar_t )

計算機程式語言 Lecture 17-6 國立台灣大學生物機電系 林達德 17.2 The Data Hierarchy From smallest to largest (continued) –Field: group of characters with some meaning Your name –Record: group of related fields struct or class in C++ In payroll system, could be name, SS#, address, wage Each field associated with same employee Record key: field used to uniquely identify record –File: group of related records Payroll for entire company Sequential file: records stored by key –Database: group of related files Payroll, accounts-receivable, inventory…

計算機程式語言 Lecture 17-7 國立台灣大學生物機電系 林達德 17.2 The Data Hierarchy

計算機程式語言 Lecture 17-8 國立台灣大學生物機電系 林達德 17.3 Files and Streams C++ views file as sequence of bytes –Ends with end-of-file marker When file opened –Object created, stream associated with it –cin, cout, etc. created when included Communication between program and file/device

計算機程式語言 Lecture 17-9 國立台灣大學生物機電系 林達德 17.3 Files and Streams To perform file processing –Include and –Class templates basic_ifstream (input) basic_ofstream (output) basic_fstream (I/O) –typedef s for specializations that allow char I/O ifstream ( char input) ofstream ( char output) fstream ( char I/O)

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.3 Files and Streams Opening files –Create objects from template –Derive from stream classes Can use stream methods from Ch. 15 put, get, peek, etc.

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.4 Creating a Sequential-Access File C++ imposes no structure on file –Concept of "record" must be implemented by programmer To open file, create objects –Creates "line of communication" from object to file –Classes ifstream (input only) ofstream (output only) fstream (I/O) –Constructors take file name and file-open mode ofstream outClientFile( "filename", fileOpenMode ); –To attach a file later Ofstream outClientFile; outClientFile.open( "filename", fileOpenMode);

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.4 Creating a Sequential-Access File File-open modes –ofstream opened for output by default ofstream outClientFile( "clients.dat", ios::out ); ofstream outClientFile( "clients.dat");

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.4 Creating a Sequential-Access File Operations –Overloaded operator! !outClientFile Returns nonzero (true) if badbit or failbit set –Opened non-existent file for reading, wrong permissions –Overloaded operator void* Converts stream object to pointer 0 when when failbit or badbit set, otherwise nonzero –failbit set when EOF found while ( cin >> myVariable ) –Implicitly converts cin to pointer –Loops until EOF

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.4 Creating a Sequential-Access File End-of-file key combinations for various popular computer systems.

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.4 Creating a Sequential-Access File Operations –Writing to file (just like cout ) outClientFile << myVariable –Closing file outClientFile.close() Automatically closed when destructor called

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.4 Creating a Sequential-Access File Use caution when opening an existing file for output (ios::out), especially when you want to preserve the file ’ s contents, which will be discarded without warning. Common Programming Error 17.1

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.4 Creating a Sequential-Access File Not opening a file before attempting to reference it in a program will result in an error. Common Programming Error 17.2

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.4 Creating a Sequential-Access File Closing files explicitly when the program no longer needs to reference them can reduce resource usage (especially if the program continues execution after closing the files). Performance Tip 17.1

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.4 Creating a Sequential-Access File Open a file for input only (using ios::in) if the file ’ s contents should not be modified. This prevents unintentional modification of the file ’ s contents and is an example of the principle of least privilege. Good Programming Practice 17.1

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_04.cpp (1 of 2) Notice the the header files required for file I/O. ofstream object created and used to open file "clients.dat". If the file does not exist, it is created. ! operator used to test if the file opened properly.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_04.cpp (2 of 2)

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 14.5 Reading Data from a Sequential- Access File Reading files –ifstream inClientFile( "filename", ios::in ); –Overloaded ! !inClientFile tests if file was opened properly –operator void* converts to pointer while (inClientFile >> myVariable) Stops when EOF found (gets value 0 )

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_07.cpp (1 of 3)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_07.cpp (2 of 3) Open and test file for input.Read from file until EOF found.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_07.cpp (3 of 3)

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 14.5 Reading Data from a Sequential- Access File File position pointers –Number of next byte to read/write –Functions to reposition pointer seekg (seek get for istream class) seekp (seek put for ostream class) Classes have "get" and "put" pointers –seekg and seekp take offset and direction Offset: number of bytes relative to direction Direction ( ios::beg default) –ios::beg - relative to beginning of stream –ios::cur - relative to current position –ios::end - relative to end

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 14.5 Reading Data from a Sequential- Access File Examples –fileObject.seekg(0) Goes to front of file (location 0 ) because ios::beg is default –fileObject.seekg(n) Goes to nth byte from beginning –fileObject.seekg(n, ios::cur) Goes n bytes forward –fileObject.seekg(y, ios::end) Goes y bytes back from end –fileObject.seekg(0, ios::cur) Goes to last byte –seekp similar

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 14.5 Reading Data from a Sequential- Access File To find pointer location –tellg and tellp –location = fileObject.tellg() Upcoming example –Credit manager program –List accounts with zero balance, credit, and debit

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_08.cpp (1 of 6)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_08.cpp (2 of 6)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_08.cpp (3 of 6)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_08.cpp (4 of 6) Use clear to reset eof. Use seekg to set file position pointer to beginning of file.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_08.cpp (5 of 6)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_08.cpp (6 of 6)

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.6 Updating Sequential-Access Files Updating sequential files –Risk overwriting other data –Example: change name "White" to "Worthington" Old data 300 White Jones Insert new data –Formatted text different from internal representation –Problem can be avoided, but awkward 300 White Jones Worthington 0.00ones Worthington 0.00 Data gets overwritten

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.7 Random-Access Files Instant access –Want to locate record quickly Airline reservations, ATMs –Sequential files must search through each one Random-access files are solution –Instant access –Insert record without destroying other data –Update/delete items without changing other data

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.7 Random-Access Files C++ imposes no structure on files –Programmer must create random-access files –Simplest way: fixed-length records Calculate position in file from record size and key

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.8 Creating a Random-Access File " " ( char * ) vs ( int ) –char * takes 8 bytes (1 for each character + null) –int takes fixed number of bytes (perhaps 4) 123 same size in bytes as << operator and write() –outFile << number Outputs number ( int ) as a char * Variable number of bytes –outFile.write( const char *, size ); Outputs raw bytes Takes pointer to memory location, number of bytes to write –Copies data directly from memory into file –Does not convert to char *

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.8 Creating a Random-Access File Example outFile.write( reinterpret_cast (&number), sizeof( number ) ); –&number is an int * Convert to const char * with reinterpret_cast –sizeof(number) Size of number (an int ) in bytes –read function similar (more later) –Must use write / read between compatible machines Only when using raw, unformatted data –Use ios::binary for raw writes/reads

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.8 Creating a Random-Access File It is easy to use reinterpret_cast to perform dangerous manipulations that could lead to serious execution-time errors. Error-Prevention Tip 17.1

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.8 Creating a Random-Access File Using reinterpret_cast is compiler- dependent and can cause programs to behave differently on different platforms. The reinterpret_cast operator should not be used unless absolute necessary. Portability Tip 17.1

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.8 Creating a Random-Access File A program that reads unformatted data (written by write ) must be compiled and executed on a system compatible with the program that wrote the data, because different systems may represent internal data differently. Portability Tip 17.2

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.8 Creating a Random-Access File Usually write entire struct or object to file Problem statement –Credit processing program –Store at most 100 fixed-length records –Record Account number (key) First and last name Balance –Account operations Update, create new, delete, list all accounts in a file Next: program to create blank 100-record file

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 ClientData.h (1 of 2) Class ClientData stores the information for each person. 100 blank ClientData objects will be written to a file.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 ClientData.h (2 of 2) Put limits on the size of the first and last name. accountNumber (an int ) and balance ( double ) are already of a fixed size.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 ClientData.cpp (1 of 3)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 ClientData.cpp (2 of 3)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 ClientData.cpp (3 of 3)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_12.cpp (1 of 2)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_12.cpp (2 of 2) Create a blank object. Use write to output the raw data to a file (passing a pointer to the object and its size). Open a file for raw writing using an ofstream object and ios::binary.

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 17.9 Writing Data Randomly to a Random- Access File Use seekp to write to exact location in file –Where does the first record begin? Byte 0 –The second record? Byte 0 + sizeof(object) –Any record? (Recordnum - 1) * sizeof(object)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_13.cpp (1 of 4) Open file for raw (binary) writing.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_13.cpp (2 of 4) Get account number, put into object. It has not yet been written to file.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_13.cpp (3 of 4) Position outCredit to the proper location in the file (based on the account number). Write ClientData object to file at specified position.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_13.cpp (4 of 4)

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Reading Data Sequentially from a Random-Access File read - similar to write –Reads raw bytes from file into memory –inFile.read( reinterpret_cast ( &number ), sizeof( int ) ); &number : location to store data sizeof(int) : how many bytes to read –Do not use inFile >> number with raw bytes >> expects char * Upcoming program –Output data from a random-access file –Go through each record sequentially If no data (accountNumber == 0) then skip

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_14.cpp (1 of 3)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_14.cpp (2 of 3) Read sizeof(ClientData) bytes and put into object client. This may be an empty record. Loop exits if there is an error reading ( inCredit == 0 ) or EOF is found ( inCredit.eof() == 1 )

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 fig17_14.cpp (3 of 3)

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Case Study: A Transaction- Processing Program Instant access for bank accounts –Use random access file (data in client.dat ) Give user menu –Option 1: store accounts to print.txt –Option 2: update record Account Last Name First Name Balance 29 Brown Nancy Dunn Stacey Barker Doug Smith Dave Stone Sam Enter account to update ( ): Barker Doug 0.00 Enter charge (+) or payment (-): Barker Doug 87.99

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Case Study: A Transaction- Processing Program Menu options (continued) –Option 3: add new record –Option 4: delete record To open file for reading and writing –Use fstream object –"Or" file-open modes together fstream inOutCredit( "credit.dat", ios::in | ios::out ); Enter new account number ( ): 22 Enter lastname, firstname, balance ? Johnston Sarah Enter account to delete ( ): 29 Account #29 deleted.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (1 of 10)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (2 of 10) Open file for reading and writing ( fstream object needed).

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (3 of 10)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (4 of 10) Displays menu and returns user's choice.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (5 of 10) Go to front of file, read account data, and print record if not empty. Note that outputLine takes an ostream object (base of ofstream ). It can easily print to a file (as in this case) or cout. This is fstream (I/O) because we must read the old balance, update it, and write the new balance.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (6 of 10)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (7 of 10) This is fstream because we read to see if a non-empty record already exists. If not, we write a new record.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (8 of 10) fstream because we read to check if the account exits. If it does, we write blank data (erase it). If it does not exist, there is no need to delete it.

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (9 of 10)

Outline 計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Fig17_15.cpp (10 of 10) outputLine is very flexible, and can output to any ostream object (such as a file or cout ).

計算機程式語言 Lecture 國立台灣大學生物機電系 林達德 Input/Output of Objects I/O of objects –Chapter 8 (overloaded >> ) –Only object's data transmitted Member functions available internally –When objects stored in file, lose type info (class, etc.) Program must know type of object when reading –One solution When writing, output object type code before real object When reading, read type code –Call proper overloaded function ( switch )