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.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES USING C++ Chapter 5
Advertisements

CPS120: Introduction to Computer Science Lecture 15 B Data Files.
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.
 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.
 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.
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
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.
1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC.
Chapter 8 Data File Basics.
1 Today’s Objectives  Announcements The Final Exam will be on Monday, 31-Jul, at 6 p.m. – There is no alternate time and no makeup!  Intro to the Standard.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
1 Today’s Objectives  Announcements Homework #2 is due next Monday, 26-Jun, at the beginning of class Midterm Exam is Monday, 26-Jun – over material in.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
 2008 Pearson Education, Inc. All rights reserved File Processing.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
“After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more.
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.
I/O in C++ October 7, Junaed Sattar. Stream I/O a stream is a flow of bytes/characters/ints or any type of data input streams: to the program output.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
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.
1 Today’s Objectives  Announcements Turn in Homework 4 Quiz 4 will be on Wednesday, July 19 – It will have questions about inheritance, polymorphism,
DCT1063 Programming 2 CHAPTER 3 FILE INPUT AND FILE OUTPUT Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
1 Today’s Objectives  Announcements Homework #5 is due today. Since this date is so close to the end of the semester, no late assignments will be accepted.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Managers and “mentors” identified on projects page. All member accounts created and projects populated.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Learners Support Publications Working with Files.
Lecture 14 Arguments, Classes and Files. Arguments.
Streams and File Processing in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
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)
CPS120 Introduction to Computer Science Exam Review Lecture 18.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
Programming with ANSI C ++
17 File Processing.
Today’s Objectives 5-Jul-2006 Announcements
Tutorial4us.com File Handling in C++ Tutorial4us.com.
CISC/CMPE320 - Prof. McLeod
CPSC 231 D.H. C++ File Processing
17 File Processing.
Interactive I/O Input from keyboard Must prompt user User friendly
17 File Processing.
files Dr. Bhargavi Goswami Department of Computer Science
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
CHAPTER 4 File Processing.
C++ Programming Lecture 8 File Processing
Today’s Objectives 28-Jun-2006 Announcements
Presentation transcript:

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 will be accepted and will NOT be accepted!  Quiz #4  File Processing (Ch. 17) Files and streams Reading from files Writing to files Adding structure to files Using seekg, seekp, tellg, and tellp  Data Structures (Ch. 21) Self-referential structures and classes Linked lists 19-Jul-2006

2 Quiz #4 Closed book 20 minutes Please clear your desks and log off from the computer

3 File Processing Chapter 17

4 Files and Streams  File Used to store data Storing data in a file makes the data “persistent”  File = a sequence of bytes Stream = a sequence of bytes When a file is opened, a stream object is associated with the file The stream object connects the file with your program File Processing (Deitel, 844)

5 File Stream Classes and Header   ifstream Used for input from a file From the template class basic_ifstream<>  ofstream Used for output from a file From the template class basic_ofstream<>  fstream Used for both output and input with a file From the template class basic_fstream<> File Processing (Deitel, 845)

6 Reading from a File char *filename = "movies.dat"; ifstream inFile( filename ); //open for reading File Processing (Deitel, 847) Name of the class that is used for input from a file Name of the stream object Filename as a C-style string

7 Reading from a File char *filename = "movies.dat"; ifstream inFile( filename ); //open for reading if( !inFile ) { cerr << "Unable to open " << filename << endl; } File Processing (Deitel, 847) It’s a good idea to check whether the file was opened successfully! Use operator! to check the state of the stream object Checks the failbit

8 Reading from a File char *filename = "movies.dat"; ifstream inFile( filename ); //open for reading if( !inFile ) { cerr << "Unable to open " << filename << endl; } else { while( !inFile.eof() ) { Movie tempMovie; inFile >> tempMovie; //reading from the file store.addRentalItem(tempMovie); } File Processing (Deitel, 847) A stream’s eof() function returns true if the end of the stream has been reached.

9 Reading from a File char *filename = "movies.dat"; ifstream inFile( filename ); //open for reading if( !inFile ) { cerr << "Unable to open " << filename << endl; } else { while( !inFile.eof() ) { Movie tempMovie; inFile >> tempMovie; //reading from the file store.addRentalItem(tempMovie); } inFile.close(); } File Processing (Deitel, 847) What would be likely to happen if we did not explicitly close the file? Hint: “infile” is an object.

10 Writing to a File char *filename = "customers.dat"; ofstream outFile( filename ); //open for writing File Processing (Deitel, 847) Name of the class that is used for output to a file Name of the stream object Filename as a C-style string

11 Writing to a File char *filename = "customers.dat"; ofstream outFile( filename ); //open for writing if( !outFile ) { cerr << "Unable to open " << filename << endl; } File Processing (Deitel, 847) Check whether the file was opened successfully!

12 Writing to a File char *filename = "customers.dat"; ofstream outFile( filename ); //open for writing if( !outFile ) { cerr << "Unable to open " << filename << endl; } else { for( int i=0; i<sz; ++i ){ outFile << myData[i].getID() << '\n'; outFile << myData[i].getFirstName() << '\n'; outFile << myData[i].getLastName(); if( i < sz - 1 ) outFile << '\n'; } File Processing (Deitel, 847) Write the data to the file.

13 Writing to a File char *filename = "customers.dat"; ofstream outFile( filename ); //open for writing if( !outFile ) { cerr << "Unable to open " << filename << endl; } else { for( int i=0; i<sz; ++i ){ outFile << myData[i].getID() << '\n'; outFile << myData[i].getFirstName() << '\n'; outFile << myData[i].getLastName(); if( i < sz - 1 ) outFile << '\n'; } outFile.close(); } File Processing (Deitel, 847)

14 Opening Files  A stream object can be created without opening a file ofstream outFile;  Then it can be opened later outFile.open("customers.dat");  If a file is opened for output and it does not already exist, a new file will be created automatically File Processing (Deitel, 848; Lippman, 1097)

15 Appending to a File  By default, when an ofstream object is opened for output, all data already stored in the file is discarded  To keep the data that is in the file and add more data to the end, open the file in append mode ofstream outFile( "customers.dat", ios::app ); File Processing (Deitel, 847; Lippman, 1097) Specifies the file open mode, see Fig. 17.5, page 847. ios::app specifies append mode ios::out specifies output mode, discard the content

16 Using Objects of fstream  fstream is used for both input from a file and output to a file  Use the mode argument to specify whether input, output, or both fstream io("customers.dat", ios::in|ios::app ); File Processing (Deitel, 847; Lippman, 1102) Specify more than one mode by using the bitwise OR operator

17 Unstructured Streams  If we write data to a file as an unstructured byte stream, we may not be able to retrieve it easily  Example If we have an array of Customer objects and we write them to a file like this: for( int i=0; i<sz; ++i ){ outFile << myData[i].getID(); outFile << myData[i].getFirstName(); outFile << myData[i].getLastName(); } Then the bytes will be written as an unstructured byte stream, and we will not be able to separate the data when the file is read 1001AlanTuring1002CharlesBabbage File Processing (Deitel, 844; Folk, 119)

18 Fields and Records  When working with files, the data is said to be composed of fundamental units called “fields” and “records”  Field = the smallest unit of meaningful data Examples: “firstName” and “lastName”  Record = the set of fields that belong together Example: each Customer object is a record that contains several fields File Processing (Deitel, 843; Folk, 120–125)

19 Adding Structure to Files  If the data is structured inside the file (i.e., the fields and records are separated), then the data can be retrieved or changed easily  There are many ways to add structure to a file  Common methods to keep fields separated Use fields that have a set length 1001 Alan Turing 1002 CharlesBabbage Place a delimiter at the end of each field 1001 Alan Turing 1002 Charles Babbage File Processing (Deitel, 843; Folk, 120–125)

20 Structured Records  Record = the set of fields that belong together  Usually, a record is equivalent to the data for one object  Common methods to keep records separated Use records that have a set length 1001 Alan Turing 1002 CharlesBabbage Make records a set number of fields 1001 Alan Turing 1002 Charles Babbage File Processing (Deitel, 843; Folk, 120–126)

21 Retrieving Data  When a file is structured, we can retrieve its data easily  Sequentially Read data from the beginning to the end, inserting it into variables or objects  Randomly Go directly to a specific record and read it seekg File Processing (Deitel, 843; Folk, 120–126)

22 Retrieving Data Sequentially File Processing (Deitel, 843; Folk, 120–126) 1001 Turing Alan 1002 Babbage Charles Example file structure: Fields are separated by ‘ \n ’ Each record has three lines string ID, lName, fName; ifstream inFile( "customers.dat" ); if( !inFile ) cerr << "Unable to open file." << endl; else { while( !inFile.eof() ) { inFile >> ID; inFile >> lName; inFile >> fName; Customer tempCustomer( ID, lName, fName ); store.addCustomer(tempCustomer); } inFile.close(); }

23 Retrieving Data Sequentially File Processing (Deitel, 843; Folk, 120–126) 1001 Turing Alan 1002 Babbage Charles Example file structure: Fields are separated by ‘ \n ’ Each record has three lines string ID, lName, fName; ifstream inFile( "customers.dat" ); if( !inFile ) cerr << "Unable to open file." << endl; else { while( !inFile.eof() ) { inFile >> ID; inFile >> lName; inFile >> fName; Customer tempCustomer( ID, lName, fName ); store.addCustomer(tempCustomer); } inFile.close(); }

24 Using seekg seekg() Member function of the istream class First argument is the number of the byte in the file that the next input will get Second argument is optional, and it is the direction for positioning, default is the beginning of the stream – ios::beg, ios::cur, ios::end Example string temp; ifstream inFile("customers.dat"); inFile.seekg(10); inFile >> temp; //string beginning at byte 10 File Processing (Deitel, 851; Lippman, 1102)

25 Retrieving Data Randomly File Processing (Deitel, 851–826) 1001 Turing Alan 1002 Babbage Charles 1003 Lovelace Ada Example file structure: Fields separated by whitespace Each record has 23 bytes const int RECORDSIZE = 23; long recordNumber = 0; string ID, lName, fName; ifstream inFile( "customers.dat" ); if( !inFile ) cerr << "Unable to open file." << endl; else{ cout << "Enter the number of a record: "; cin >> recordNumber; while( recordNumber > -1 && recordNumber < 2 ){ inFile.seekg( recordNumber * RECORDSIZE, ios::beg ); inFile >> ID >> lName >> fName; Customer tempCustomer( ID, lName, fName ); cout << "The customer is: " << tempCustomer << endl; cout << "Enter the number of a record: "; cin >> recordNumber; } inFile.close(); }

26 Using seekp seekp() Member function of the ostream class First argument is the number of the byte in the file where the next output will start Second argument is optional, and it is the direction for positioning, default is the beginning of the stream – ios::beg, ios::cur, ios::end Example const int RECORDSIZE = 23; ofstream outFile("customers.dat"); outFile.seekp( n * RECORDSIZE ); outFile.write("1005 ",5);//changes the ID File Processing (Deitel, 851; Lippman, 1102)

27 Using tellg, tellp tellg() Member function of the istream class Returns the current byte in the input file Example long pos = inFile.tellg(); tellp() Member function of the ostream class Returns the current byte in the output file  Used to mark a position in the file so that the program can return to it later inFile.seekg( pos ); File Processing (Deitel, 851; Lippman, 1102)

28 Data Structures Chapter 21

29 Data Structure “ A systematic way of organizing and accessing data” in a computer’s memory Data Structures (Goodrich, 108)  Simple data structures – an array, a vector, a struct, a class  More complex data structures often use self-referential structures or classes

30 Self-Referential Struct  Contains a data field that holds a data value  Contains one or more data fields that hold a pointer to another struct object of the same type struct Node { char element; Node *next; }; Data Structures (Deitel, 1000)

31 Struct with a Constructor  In C++, a struct can have a constructor struct Node { char element; Node *next; Node(char e=' ',Node *p=NULL):element(e),next(p){} }; Data Structures (Deitel, 1000)

32 Self-Referential Class  Contains a data field that holds a data value  Contains one or more data fields that hold a pointer to another object of the same type class CNode { public: CNode(char e=' ',CNode *p=NULL):element(e),next(p){} void setElement( char c ){ element = c; } char getElement(){ return element; } void setNext( CNode *p ){ next = p; } CNode *getNext(){ return next; } private: char element; CNode *next; }; Data Structures (Deitel, 1000)

33 Building a Data Structure with Self-Referential Objects Self-referential objects can be linked together to hold a collection of related data Similar to an array Linked list – a type of data structure built from self- referential objects Linked List Data Structures (Deitel, 1000) Collection of objects Each object has a pointer that points to the next object

34 Similarities and Differences Between Arrays and Linked Lists Similarities Both store data in memory Both store data in a sequence Differences Array is one block of contiguous memory List is a collection of scattered memory cells Array Linked List Data Structures (Deitel, 1000)

35 Linked List Example  We normally use a pointer to keep track of the location of the first node, called the “head node”  Each subsequent node in the list is accessed by the pointer member inside the previous node  We often use another pointer to keep track of the last node, called the “tail”  The pointer in the last node is set to NULL NULL struct Node { char element; Node *next; }; *next; struct Node { char element; Node *next; }; *next; struct Node { char element; Node *next; }; *next; pHead Data Structures (Deitel, 1000) pTail

36 Arrays vs. Linked Lists Arrays Advantages Simple Fast performance Drawbacks Size is fixed – we use up the space even if we don’t need it Size must be determined in advance Linked Lists Advantages No fixed size – use only space we need We can add more nodes at any time Drawbacks Additional time for allocating memory during program execution More complicated code Data Structures (Deitel, 1000)

37 Using a Linked List  If we create a class for our linked list, then we can encapsulate all of the list’s data and the operations that we can do with the list  Operations (member functions) size push_front pop_front printList  Data members size A pointer to the head node Data Structures (Deitel, 1000)

38 Starting a List Class class List{ private: struct Node { char element; Node *next; Node(char e=' ',Node *p=NULL):element(e),next(p){} }; public: List(); int size(); void push_front( char e ); void pop_front(); void printList(); private: int sz; Node *pHead; }; Data Structures (Deitel, 1000)

39 Defining Some Member Functions List::List(){ sz = 0; pHead = NULL; } int List::size(){ return sz; } Data Structures (Deitel, 1000)

40 Visualizing push_front Data Structures (Deitel, 1000, Goodrich, 177) pHead NULL f next g next h next

41 Visualizing push_front Data Structures (Deitel, 1000, Goodrich, 177) next 1. pHead e NULL f next g next h next //Create a new node //Put the data into its data element //Put the address in pHead into its “next” pointer

42 Visualizing push_front Data Structures (Deitel, 1000, Goodrich, 177) next 1. pHead e NULL f next g next h next pHead e next NULL f next g next h next 2. //Make pHead point to the new node

43 Visualizing push_front Data Structures (Deitel, 1000, Goodrich, 177) next 1. pHead e NULL f next g next h next pHead e next NULL f next g next h next 2. pHead e next NULL f next g next h next 3.

44 Coding push_front //Create a new node //Put the data into its data element //Put the address in pHead into its “next” pointer pHead = v; //Make pHead point to the new node Node *v = new Node( 'e', pHead ); Data Structures (Deitel, 1000, Goodrich, 177) sz++; //Increase the size

45 Visualizing printList  We use a temporary node to print the elements stored in a linked list Data Structures (Deitel, 1000, Goodrich, 177) pHead NULL f next g next h next current //Start at the head and print its element next

46 Visualizing printList  We use a temporary node to print the elements stored in a linked list Data Structures (Deitel, 1000, Goodrich, 177) pHead NULL f next g next h next //Start at the head and print its element //Then get the next node and print its element current next

47 Visualizing printList  We use a temporary node to print the elements stored in a linked list Data Structures (Deitel, 1000, Goodrich, 177) pHead NULL f next g next h next //Start at the head and print its element //Then get the next node and print its element current next

48 Visualizing printList  We use a temporary node to print the elements stored in a linked list Data Structures (Deitel, 1000, Goodrich, 177) pHead NULL f next g next h next //Start at the head and print its element //Then get the next node and print its element //Stop when it’s NULL current next

49 Coding printList void List::printList(){ Node *current = pHead; while( current ){ cout element << " "; current = current->next; } Data Structures (Deitel, 1000, Goodrich, 177) Start at the head Stop if it’s NULL Print the element Get the next node

50 Visualizing pop_front //Save the address of the current head as “old head” //Make the head pointer point to node #2 //Delete the old head 2. pHead e next NULL f next g next h next 1. oldHead = pHead e next NULL f next g next h next oldHead Data Structures (Deitel, 1000, Goodrich, 177)

51 Coding pop_front //Save the address of the current head as “old head” //Make the head pointer point to node #2 //Delete the old head //Reduce the size Node *oldHead = pHead; //Hold it temporarily pHead = pHead->next; //Switch the pointer delete oldHead; //Recover the memory sz--; //Reduce the size Data Structures (Deitel, 1000, Goodrich, 177)

52 The Destructor  Every node in the list was created with new, so every node must be deleted List::~List(){ while( sz > 0 ){ pop_front(); } Data Structures (Deitel, 1000, Goodrich, 177)

53 References C++ Language Reference (MS Visual C++ Online Help), Redmond, Washington: Microsoft Corporation, Deitel, H. M., and P. J. Deitel, C++ How to Program, Fifth Edition. Upper Saddle River, NJ: Prentice Hall, Goodrich, M. T., R. Tamassia, and D. Mount, Data Structures and Algorithms in C++. Hoboken, NJ: John Wiley & Sons, Inc., Josuttis, Nicolai M., The C++ Standard Library, A Tutorial and Reference. Boston: Addison-Wesley, 1999.