Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 13 Advanced.

Slides:



Advertisements
Similar presentations
CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
File streams Chapter , ,
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
Chapter 5: Loops and Files.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
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.
Chapter 3: Input/Output
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 13: Advanced File.
COIT29222-Structured Programming Lecture Week 12  Reading: Textbook (4 th Ed.), Chapter 14 Textbook (6 th Ed.), Chapter 17 Study Guide Book 3, Module.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
C++ Streams Lecture-2.
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
Topics 1.File Basics 2.Output Formatting 3.Passing File Stream Objects to Functions 4.More Detailed Error Testing 5.Member Functions for Reading and 6.Writing.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
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.
C++ FILE I/O.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
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
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Member Functions for Reading and Writing Files 12.5.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Chapter 3: Input/Output
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.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 CSC241: Object Oriented Programming Lecture No 32.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
Learners Support Publications Working with Files.
FILE HANDLING(WORKING WITH FILES) FILE- A file is a collection of related data stored in a particular area on the disk. STREAMS- interface between the.
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)
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.
Starting Out with C++ 1 Chapter 12: File Operations What is a File? A file is a collection on information, usually stored on some electronic medium. Information.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
CS212: Object Oriented Analysis and Design
Programming with ANSI C ++
Topic 2 Input/Output.
17 File Processing.
Chapter 13: Advanced File and I/O Operations
Input and Output Chapter 3.
Standard Input/Output Streams
Standard Input/Output Streams
Lecture 5A File processing Richard Gesick.
17 File Processing.
files Dr. Bhargavi Goswami Department of Computer Science
Chapter 13: Advanced File and I/O Operations
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Chapter 3 Input output.
CPS120: Introduction to Computer Science
C++ Programming: chapter 6 – iostream
C++ Programming Lecture 8 File Processing
Presentation transcript:

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 13 Advanced File and I/O Operations

Chapter 13 Starting Out with C++: Early Objects 5/e slide 2 © 2006 Pearson Education. All Rights Reserved Topics 13.1 Files 13.2 Output Formatting 13.3 Passing File Stream Objects to Functions 13.4 More Detailed Error Testing 13.5 Member Functions for Reading and Writing Files

Chapter 13 Starting Out with C++: Early Objects 5/e slide 3 © 2006 Pearson Education. All Rights Reserved Topics (continued) 13.6 Working with Multiple Files 13.7 Binary Files 13.8 Creating Records with Structures 13.9 Random-Access Files Opening a File for Both Input and Output

Chapter 13 Starting Out with C++: Early Objects 5/e slide 4 © 2006 Pearson Education. All Rights Reserved 13.1 Files Set of data stored on a computer, often on a disk drive Programs can read from, write to files Used in many applications: –Word processing –Databases –Spreadsheets –Compilers

Chapter 13 Starting Out with C++: Early Objects 5/e slide 5 © 2006 Pearson Education. All Rights Reserved File Naming Conventions Different systems may have different requirements on how to name a file: –MS-DOS: up to 8 characters, a dot, up to a 3 character extension. No spaces. Example: sales.dat Extension often indicates purpose of file: –.doc : Microsoft Word file –.cpp : C++ source file –.h : C++ header file

Chapter 13 Starting Out with C++: Early Objects 5/e slide 6 © 2006 Pearson Education. All Rights Reserved Steps to Using a File 1.Open the file 2.Use (read from, write to) the file 3.Close the file

Chapter 13 Starting Out with C++: Early Objects 5/e slide 7 © 2006 Pearson Education. All Rights Reserved File Stream Objects Use of files requires file stream objects There are three types of file stream objects (1) ifstream objects: used for input (2) ofstream objects: used for output (3) fstream objects: used for both input and output

Chapter 13 Starting Out with C++: Early Objects 5/e slide 8 © 2006 Pearson Education. All Rights Reserved File Names File name can be a full pathname to file: c:\data\student.dat tells compiler exactly where to look File name can also be simple name: student.dat this must be in the same directory as the program executable, or in the compiler's default directory

Chapter 13 Starting Out with C++: Early Objects 5/e slide 9 © 2006 Pearson Education. All Rights Reserved Opening a File A file is known to the system by its name To use a file, a program needs to connect a suitable stream object to the file. This is known as opening the file Opening a file is achieved through the open member function of a file stream object

Chapter 13 Starting Out with C++: Early Objects 5/e slide 10 © 2006 Pearson Education. All Rights Reserved Opening a File for Input Create an ifstream object in your program ifstream inFile; Open the file by passing its name to the stream’s open member function inFile.open("myfile.dat");

Chapter 13 Starting Out with C++: Early Objects 5/e slide 11 © 2006 Pearson Education. All Rights Reserved Getting File Names from Users Define file stream object, variable to hold file name ifstream inFile; char FileName(81); Prompt user to enter filename and read the filename cout << "Enter filename: "; cin.getline(FileName, 81); Open the file inFile.open(FileName);

Chapter 13 Starting Out with C++: Early Objects 5/e slide 12 © 2006 Pearson Education. All Rights Reserved Opening a File for Output Create an ofstream object in your program ofstream outFile; Open the file by passing its name to the stream’s open member function outFile.open("myfile.dat");

Chapter 13 Starting Out with C++: Early Objects 5/e slide 13 © 2006 Pearson Education. All Rights Reserved The fstream Object fstream object can be used for either input or output fstream file; To use fstream for input, specify ios::in as the second argument to open file.open("myfile.dat",ios::in); To use fstream for output, specify ios::out as the second argument to open file.open("myfile.dat",ios::out);

Chapter 13 Starting Out with C++: Early Objects 5/e slide 14 © 2006 Pearson Education. All Rights Reserved Opening a File for Input and Output fstream object can be used for both input and output at the same time Create the fstream object and specify both ios::in and ios::out as the second argument to the open member function fstream file; file.open("myfile.dat", ios::in|ios::out);

Chapter 13 Starting Out with C++: Early Objects 5/e slide 15 © 2006 Pearson Education. All Rights Reserved Opening Files with Constructors Stream constructors have overloaded versions that take the same parameters as open These constructors open the file, eliminating the need for a separate call to open fstream inFile("myfile.dat", ios::in);

Chapter 13 Starting Out with C++: Early Objects 5/e slide 16 © 2006 Pearson Education. All Rights Reserved File Open Modes File open modes specify how a file is opened and what can be done with the file once it is open ios::in and ios::out are examples of file open modes, also called file mode flags File modes can be combined and passed as second argument of open member function

Chapter 13 Starting Out with C++: Early Objects 5/e slide 17 © 2006 Pearson Education. All Rights Reserved File Mode Flags ios::app create new file, or append to end of existing file ios::ate go to end of existing file; write anywhere ios::binary read/write in binary mode (not text mode) ios::in open for input ios::out open for output

Chapter 13 Starting Out with C++: Early Objects 5/e slide 18 © 2006 Pearson Education. All Rights Reserved File Open Modes Not all combinations of file open modes make sense ifstream and ofstream have default file open modes defined for them, hence the second parameter to their open member function is optional

Chapter 13 Starting Out with C++: Early Objects 5/e slide 19 © 2006 Pearson Education. All Rights Reserved Default File Open Modes ofstream: –open for output only –file cannot be read from –file created if no file exists –file contents erased if file exists ifstream : –open for input only –file cannot be written to –open fails if file does not exist

Chapter 13 Starting Out with C++: Early Objects 5/e slide 20 © 2006 Pearson Education. All Rights Reserved Detecting File Open Errors Two methods for detecting if a file open failed (1) Call fail() on the stream inFile.open("myfile"); if (inFile.fail()) { cout << "Can't open file"; exit(1); }

Chapter 13 Starting Out with C++: Early Objects 5/e slide 21 © 2006 Pearson Education. All Rights Reserved Detecting File Open Errors (2) Test the status of the stream using the ! operator inFile.open("myfile"); if (!inFile) { cout << "Can't open file"; exit(1); }

Chapter 13 Starting Out with C++: Early Objects 5/e slide 22 © 2006 Pearson Education. All Rights Reserved Using fail() to detect eof Example of reading all integers in a file //attempt a read int x; infile >> x; while (!infile.fail()) { //success, so not eof cout << x; //read again infile >> x; }

Chapter 13 Starting Out with C++: Early Objects 5/e slide 23 © 2006 Pearson Education. All Rights Reserved Using >> to detect eof To detect end of file, fail() must be called immediately after the call to >> The extraction operator returns the same value that will be returned by the next call to fail: - ( infile >> x ) is nonzero if >> succeeds - ( infile >> x ) is zero if >> fails

Chapter 13 Starting Out with C++: Early Objects 5/e slide 24 © 2006 Pearson Education. All Rights Reserved Detecting End of File Reading all integers in a file int x; while (infile >> x) { // read was successful cout >> x; // go to top of loop and // attempt another read }

Chapter 13 Starting Out with C++: Early Objects 5/e slide 25 © 2006 Pearson Education. All Rights Reserved 13.2 Output Formatting Can format with I/O manipulators: they work with file objects just like they work with cout Can format with formatting member functions The ostringstream class allows in-memory formatting into a string object before writing to a file

Chapter 13 Starting Out with C++: Early Objects 5/e slide 26 © 2006 Pearson Education. All Rights Reserved I/O Manipulators left, right left or right justify output oct, dec, hex display output in octal, decimal, or hexadecimal endl, flush write newline ( endl only) and flush output showpos, noshowpos do, do not show leading + with non-negative numbers showpoint, noshowpoint do, do not show decimal point and trailing zeroes

Chapter 13 Starting Out with C++: Early Objects 5/e slide 27 © 2006 Pearson Education. All Rights Reserved More I/O Manipulators fixed, scientific use fixed or scientific notation for floating-point numbers setw(n) sets minimum field output width to n setprecision(n) sets floating-point precision to n setfill(ch) uses ch as fill character

Chapter 13 Starting Out with C++: Early Objects 5/e slide 28 © 2006 Pearson Education. All Rights Reserved Formatting with Member Functions Can also use stream object member functions to format output: gradeFile.width(3); // like // setw(3) Names of member functions may differ from manipulators.

Chapter 13 Starting Out with C++: Early Objects 5/e slide 29 © 2006 Pearson Education. All Rights Reserved Formatting with Member Functions Member FunctionManipulator or Meaning width(n)setw(n) precision(n)setprecision(n) setf() set format flags unsetf() disable format flags

Chapter 13 Starting Out with C++: Early Objects 5/e slide 30 © 2006 Pearson Education. All Rights Reserved sstream Formatting 1)To format output into an in-memory string object, include the sstream header file and create an ostringstream object #include ostringstream outStr;

Chapter 13 Starting Out with C++: Early Objects 5/e slide 31 © 2006 Pearson Education. All Rights Reserved sstream Formatting 2)Write to the ostringstream object using I/O manipulators, all other stream member functions: outStr << showpoint << fixed << setprecision(2) << 'S'<< amount;

Chapter 13 Starting Out with C++: Early Objects 5/e slide 32 © 2006 Pearson Education. All Rights Reserved sstream Formatting 3)Access the C-string inside the ostringstream object by calling its str member function cout << outStr.str();

Chapter 13 Starting Out with C++: Early Objects 5/e slide 33 © 2006 Pearson Education. All Rights Reserved 13.3 Passing File Stream Objects to Functions File stream objects keep track of current read or write position in the file Always use pass a file object as parameter to a function using pass by reference

Chapter 13 Starting Out with C++: Early Objects 5/e slide 34 © 2006 Pearson Education. All Rights Reserved Passing File Stream Objects to Functions //print all integers in a file to screen void printFile(ifstream &in) { int x; while(in >> x) { out << x << " "; } }

Chapter 13 Starting Out with C++: Early Objects 5/e slide 35 © 2006 Pearson Education. All Rights Reserved 13.4 More Detailed Error Testing Streams have error bits (flags) that are set by every operation to indicate success or failure of the operation, and the status of the stream Stream member functions report on the settings of the flags

Chapter 13 Starting Out with C++: Early Objects 5/e slide 36 © 2006 Pearson Education. All Rights Reserved Error State Bits Can examine error state bits to determine file stream status ios::eofbit set when end of file detected ios::failbit set when operation failed ios::hardfail set when an irrecoverable error occurred ios::badbit set when invalid operation attempted ios::goodbit set when no other bits are set

Chapter 13 Starting Out with C++: Early Objects 5/e slide 37 © 2006 Pearson Education. All Rights Reserved Error Bit Reporting Functions eof() true if eofbit set, false otherwise fail() true if failbit or hardfail set, false otherwise bad() true if badbit set, false otherwise good() true if goodbit set, false otherwise clear() clear all flags (no arguments), or clear a specific flag

Chapter 13 Starting Out with C++: Early Objects 5/e slide 38 © 2006 Pearson Education. All Rights Reserved 13.5 Member Functions for Reading and Writing Files Unlike the extraction operator >>, these reading functions do not skip whitespace: getline : read a line of input get : reads a single character seekg : goes to beginning of input file

Chapter 13 Starting Out with C++: Early Objects 5/e slide 39 © 2006 Pearson Education. All Rights Reserved getline Member Function getline(char s[ ], int max, char stop ='\n') –char s[ ]: Character array to hold input –int max : Maximum number of characters to read –char stop : Terminator to stop at if encountered before max number of characters is read. Default is '\n'

Chapter 13 Starting Out with C++: Early Objects 5/e slide 40 © 2006 Pearson Education. All Rights Reserved Single Character Input get(char &ch) Read a single character from the input stream. Does not skip whitespace. ifstream inFile; char ch; inFile.open("myFile"); inFile.get(ch); cout << "Got " << ch;

Chapter 13 Starting Out with C++: Early Objects 5/e slide 41 © 2006 Pearson Education. All Rights Reserved Single Character Output put(char ch) Output a character to a file Example ofstream outFile; outFile.open("myfile"); outFile.put('G');

Chapter 13 Starting Out with C++: Early Objects 5/e slide 42 © 2006 Pearson Education. All Rights Reserved Single Character I/O To copy an input file to an output file char ch; infile.get(ch); while (!infile.fail()) { outfile.put(ch); infile.get(ch); } infile.close(); outfile.close();

Chapter 13 Starting Out with C++: Early Objects 5/e slide 43 © 2006 Pearson Education. All Rights Reserved Moving About in Input Files seekg(offset, place) Move to a given offset relative to a given place in the file –offset : number of bytes from place, specified as a long –place : location in file from which to compute offset ios::beg : beginning of file ios::end : end of the file ios::cur : current position in file

Chapter 13 Starting Out with C++: Early Objects 5/e slide 44 © 2006 Pearson Education. All Rights Reserved Rewinding a File To move to beginning of file, seek to an offset of zero from beginning of file inFile.seekg(0L, ios::beg); Error or eof bits will block seeking to the beginning of file. Clear bits first: inFile.clear(); inFile.seekg(0L, ios::beg);

Chapter 13 Starting Out with C++: Early Objects 5/e slide 45 © 2006 Pearson Education. All Rights Reserved 13.6 Working with Multiple Files Can have more than one file open at a time in a program Files may be open for input or output Need to define stream object for each file

Chapter 13 Starting Out with C++: Early Objects 5/e slide 46 © 2006 Pearson Education. All Rights Reserved 13.7 Binary Files Binary files store data in the same format that a computer has in main memory Text files store data in which numeric values have been converted into strings of ASCII characters Files are opened in text mode (as text files) by default

Chapter 13 Starting Out with C++: Early Objects 5/e slide 47 © 2006 Pearson Education. All Rights Reserved Using Binary Files Pass the ios::binary flag to the open member function to open a file in binary mode infile.open("myfile.dat",ios::binary); Reading and writing of binary files requires special read and write member functions read(char *buffer, int numberBytes) write(char *buffer, int numberBytes)

Chapter 13 Starting Out with C++: Early Objects 5/e slide 48 © 2006 Pearson Education. All Rights Reserved Using read and write read(char *buffer, int numberBytes) write(char *buffer, int numberBytes) buffer: holds an array of bytes to transfer between memory and the file numberBytes : the number of bytes to transfer Address of the buffer needs to be cast to char * using reinterpret_cast

Chapter 13 Starting Out with C++: Early Objects 5/e slide 49 © 2006 Pearson Education. All Rights Reserved Using write To write an array of 2 doubles to a binary file ofstream outFile("myfile", ios:binary); double d[2] = {12.3, 34.5}; outFile.write( reinterpret_cast (d), sizeof(d) );

Chapter 13 Starting Out with C++: Early Objects 5/e slide 50 © 2006 Pearson Education. All Rights Reserved Using read To read two 2 doubles from a binary file into an array ifstream inFile("myfile", ios:binary); const int DSIZE = 10; double data[DSIZE]; inFile.read( reinterpret_cast (data), 2*sizeof(double) ); // only data[0] and data[1] contain // values

Chapter 13 Starting Out with C++: Early Objects 5/e slide 51 © 2006 Pearson Education. All Rights Reserved 13.8 Creating Records with Structures Can write structures to, read structures from files To work with structures and files, –use binary file flag upon open –use read, write member functions

Chapter 13 Starting Out with C++: Early Objects 5/e slide 52 © 2006 Pearson Education. All Rights Reserved Creating Records with Structures struct TestScore {int studentId; float score; char grade; }; TestScore test1[20];... // write out test1 array to a file gradeFile.write( reinterpret_cast (test1), sizeof(test1));

Chapter 13 Starting Out with C++: Early Objects 5/e slide 53 © 2006 Pearson Education. All Rights Reserved 13.9 Random-Access Files Sequential access: start at beginning of file and go through data in file, in order, to end –to access 100 th entry in file, go through 99 preceding entries first Random access: access data in a file in any order –can access 100 th entry directly

Chapter 13 Starting Out with C++: Early Objects 5/e slide 54 © 2006 Pearson Education. All Rights Reserved Random Access Member Functions seekg (seek get): used with input files seekp (seek put): used with output files Both are used to go to a specific position in a file

Chapter 13 Starting Out with C++: Early Objects 5/e slide 55 © 2006 Pearson Education. All Rights Reserved Random Access Member Functions seekg(offset,place) seekp(offset,place) offset : long integer specifying number of bytes to move place : starting point for the move, specified by ios:beg, ios::cur or ios:end

Chapter 13 Starting Out with C++: Early Objects 5/e slide 56 © 2006 Pearson Education. All Rights Reserved Random-Access Member Functions Examples: // Set read position 25 bytes // after beginning of file inData.seekg(25L, ios::beg); // Set write position 10 bytes // before current position outData.seekp(-10L, ios::cur);

Chapter 13 Starting Out with C++: Early Objects 5/e slide 57 © 2006 Pearson Education. All Rights Reserved Random Access Information tellg member function: return current byte position in input file int whereAmI; whereAmI = inFile.tellg(); tellp member function: return current byte position in output file whereAmI = outFile.tellp();

Chapter 13 Starting Out with C++: Early Objects 5/e slide 58 © 2006 Pearson Education. All Rights Reserved Opening a File for Both Input and Output File can be open for input and output simultaneously Supports updating a file: –read data from file into memory –update data –write data back to file Use fstream for file object definition: fstream gradeList("grades.dat", ios::in | ios::out);

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 13 Advanced File and I/O Operations