Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.

Slides:



Advertisements
Similar presentations
Chapter 12 Streams and File I/O Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Chapter 12 Streams and File I/O. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  I/O Streams  File I/O  Character.
Copyright © 2002 Pearson Education, Inc. Slide 1.
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.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Introducing Algorithms, Pseudocode and.
 2006 Pearson Education, Inc. All rights reserved File Processing.
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
 2006 Pearson Education, Inc. All rights reserved File Processing.
Chapter 5: Loops and Files.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
計算機概論實習 Stream Stream: sequence of bytes Input: from device (keyboard, disk drive) to memory Output: from memory to device (monitor, printer,
Chapter 8: I/O Streams and Data Files. In this chapter, you will learn about: – I/O file stream objects and functions – Reading and writing character-based.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Working with Data Files.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 13: Advanced File.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Input/Output.
Darbas su failais Arnas Terekas IT 1gr. Vilniaus universitetas Matematikos ir informatikos fakultetas.
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC.
Chapter 12 Streams and File I/O. Learning Objectives I/O Streams – File I/O – Character I/O Tools for Stream I/O – File names as input – Formatting output,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
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.
1 Streams 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.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
 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.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
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.
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
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
Learners Support Publications Working with Files.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
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)
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
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++
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
Chapter 14: Sequential Access Files
What is wrong in the following function definition
17 File Processing.
Chapter 13: Advanced File and I/O Operations
COMP 2710 Software Construction File I/O
Lecture 5A File processing Richard Gesick.
Working with Data Files
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.
Presentation transcript:

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Bitwise OR | The | is a bitwise OR In the expression abc | def, it will check each bit (bit by bit) in both values. If either of them contains a 1 in a position the result is a 1 in that position. char abc = 'A', def = 'F', ghi; 'A' = 'F' = 'A' | 'F' = = 'G' ghi = abc | def; std::cout << ghi << std::endl; G

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Bitwise AND & The & is a bitwise AND In the expression abc & def, it will check each bit (bit by bit) in both values. If both of them contains a 1 in a position the result is a 1 in that position. char abc = 'G', def = 'I', ghi; 'G' = 'I' = 'G' | 'I' = = 'A' ghi = abc & def; std::cout << ghi << std::endl; A

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved File Operations

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. File Operations File: a 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

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Using Files 1.Requires fstream header file use std::ifstream data type for input files use std::ofstream data type for output files use std::fstream data type for both input, output files 2.Can use >> / << to read from / write to a file 3.Can use eof member function to test for end of input file

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. fstream Object fstream object can be used for either input or output Must specify mode in the open statement Sample modes: std::ios::in – input std::ios::out – output Can be combined on open call: dFile.open("class.txt", std::ios::in | std::ios::out); The | (bitwise OR) causes both the in bit and the out bit to be set

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. File Access Flags

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Using Files - Example // copy 10 numbers between files // open the files std::fstream inStream("input.txt", std::ios::in); std::fstream outStream("output.txt", std::ios::out); int num; for (int idx = 0; idx < 10; idx++) { inStream >> num; // use the files outStream << num; } inStream.close(); // close the files outStream.close();

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Using Files – Example – Results for (int idx = 0; idx < 10; idx++) { inStream >> num; // use the files outStream << num; } Input file contents: Output file contents:

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Default File Open Modes std::ifstream : open for input only ( std::ios::in ) file cannot be written to open fails if file does not exist std::ofstream: open for output only ( std::ios::in ) file cannot be read from file created if no file exists file contents erased if file exists

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. More File Open Details Can use filename, flags in definition: std::ifstream gradeList("grades.txt"); std::fstream list("list.txt", std::ios::out | std::ios::in); File stream object set to 0 ( false ) if open failed: if (!gradeList)... Can also check fail member function to detect file open error: if (gradeList.fail())...

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved File Output Formatting

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. File Output Formatting Use the same techniques with file stream objects as with std::cout, for example: std::showpoint std::setw(x) std::setprecision(x) Requires iomanip to use manipulators Only sets parameters for one specific stream

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Program 12-3 – part 1 // Filename: Pr12-03.cpp // This program uses setprecision and fixed // manipulators to format file output. #include // main controls the flow of the program int main() { std::fstream dataFile; double num = ; dataFile.open("numfile.txt", std::ios::out);// Open in output mode dataFile << std::fixed;// Format for fixed-point notation dataFile << num << std::endl;// Write the number dataFile << std::setprecision(4);// Format for 4 decimal places dataFile << num << std::endl;// Write the number dataFile << std::setprecision(3);// Format for 3 decimal places dataFile << num << std::endl;// Write the number

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Program 12-3 – part 2 dataFile << std::setprecision(2);// Format for 2 decimal places dataFile << num << std::endl;// Write the number dataFile << std::setprecision(1);// Format for 1 decimal place dataFile << num << std::endl;// Write the number dataFile << std::setprecision(0);// Format for 0 decimal places dataFile << num << std::endl;// Write the number std::cout << "Done.\n"; dataFile.close();// Close the file return 0; } Contents of "numfile.txt"

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved Passing File Stream Objects to Functions

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Passing File Stream Objects to Functions It is very useful to pass file stream objects to functions Be sure to always pass file stream objects by reference // function prototype void readData(std::istream&, struct Data&); readData(infile, data); // function call // function definition void readData(std::istream &in, Data &data) { in >> data.one >> data.two >> data.three; }

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Program 12-5 – part 1 // Filename: Pr12-05.cpp // This program demonstrates how file stream objects may // be passed by reference to functions. #include // Function prototypes bool openFileIn(std::fstream &, std::string); void showContents(std::fstream &); // main controls the flow of the program int main() { std::fstream dataFile; if(openFileIn(dataFile, "demofile.txt")) { std::cout << "File opened successfully.\n"; std::cout << "Now reading data from the file.\n\n"; showContents(dataFile); dataFile.close(); std::cout << "\nDone.\n"; }

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Program 12-5 – part 2 else std::cout << "File open error!" << std::endl; return 0; } // The file stream is opened for input. The function // returns true upon success, false upon failure. bool openFileIn(std::fstream &stream, std::string name) { stream.open(name, std::ios::in); // C++ 11 stream.open(name.c_str(), std::ios::in); // C++ 98 return !stream.fail(); }

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Program 12-5 – part 3 // Function uses a loop to read each name // from the file and displays it on the screen. void showContents(std::fstream &file) { std::string line; while(file >> line) std::cout << line << std::endl; } Program Output: File opened successfully. Now reading data from the file. Jones Smith Willie Davis Done.

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved More Detailed Error Testing

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. More Detailed Error Testing Can examine error state bits to determine stream status Bits tested/cleared by stream member functions ios::eofbit set when end of file detected ios::failbit set when operation failed ios::hardfail set when error occurred and no recovery ios::badbit set when invalid operation attempted ios::goodbit set when no other bits are set

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Member Functions / Flags 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( eofbit) clear all flags (no arguments), or clear a specific flag

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. From Program 12-6 void showState(std::fstream &stream) { std::cout << "stream Status:\n"; std::cout << " eof bit: " << stream.eof() << std::endl; std::cout << " fail bit: " << stream.fail() << std::endl; std::cout << " bad bit: " << stream.bad() << std::endl; std::cout << " good bit: " << stream.good() << std::endl; stream.clear(); // Clear all bad bits }

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved Member Functions for Reading and Writing Files

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Member Functions for Reading and Writing Files Functions that may be used for input with whitespace, to perform single character I/O, or to return to the beginning of an input file Member functions: getline : reads input including whitespace get : reads a single character put : writes a single character

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. The getline Function Three arguments: Name of a input file stream object Name of a std::string object Delimiter character of your choice Examples, using the file stream object myFile, and the string objects name and address: std::getline(myFile, name); std::getline(myFile, address, '\t'); If third argument not used, '\n' is default

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Single Character I/O get : read a single character from a file char letterGrade; gradeFile.get(letterGrade); Will read any character, including whitespace put : write a single character to a file reportFile.put(letterGrade);

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved Working with Multiple Files

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. 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 or both Need to define file stream object for each file that will be open at the same time

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Working with Multiple Files Each file stream has its own set of parameters std::ofstream strm1, strm2; … // open associated files strm1 << std::fixed << std::setprecesion(2); double val = ; strm2 << val << std::endl; What will the above code output?

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

12.7 Binary Files

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. reinterpret_cast<> Previously, we used static_cast to cast one type to another. Similarly, we use reinterret_cast to cast one type of pointer to another type of pointer. In the expression: reinterpret_cast &num we cast the address of an int (which makes it a pointer) to a char pointer

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Binary Files Binary file contains unformatted, non- ASCII data Indicate by using binary flag on open: inFile.open("nums.dat", std::ios::in | std::ios::binary);

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved Binary Files Use read and write instead of > char ch; // read in a letter from file inFile.read(&ch, sizeof(ch)); // send a character to a file outFile.write(&ch, sizeof(ch)); address of where to put the data being read in. The read function expects to read char s how many bytes (characters) to read from the file The first argument of read must be a char pointer

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Binary Files To read, write non-character data, must use a typecast operator to treat the address of the data as a character address int num; // read in a binary number from a file inFile.read(reinterpret_cast &num, sizeof(num)); // send a binary value to a file outf.write(reinterpret_cast &num, sizeof(num)); treat the address of num as the address of a char

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved Creating Records with Structures

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Creating Records with Structures Can write structures to, read structures from files To work with structures and files, use std::ios::binary file flag upon open use read, write member functions

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Creating Records with Structures struct TestScore { int studentId; char name[40]; // cannot use std::string double score; char grade; }; TestScore oneTest;... // write out oneTest to a file gradeFile.write(reinterpret_cast (&oneTest), sizeof(oneTest));

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. How big is a string ? // main controls the flow of the program int main() { std::string shorty = "Short"; // std::string longy = "To be or not to be, that is the question"; std::cout << "sizeof(shorty) is " << sizeof(shorty) << " when shorty.size() is " << shorty.size() << std::endl; std::cout << "sizeof(longy) is " << sizeof(longy) << " when longy.size() is " << longy.size() << std::endl; return 0; } Results: sizeof(shorty) is 8 when shorty.size() is 5 sizeof(longy) is 8 when longy.size() is 40

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved Random-Access Files

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. 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

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Random Access Member Functions seekg (seek get): used with files open for input – seek position to read (get) from seekp (seek put): used with files open for output – seek position to write (put) to Used to go to a specific position in a file

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Random Access Member Functions seekg, seekp arguments: offset : number of bytes, as a long position : starting point to compute offset Examples: inData.seekg(25L, std::ios::beg); // set read position at 26th byte // from beginning of file outData.seekp(-10L, std::ios::cur); // set write position 10 bytes // before current position

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Important Note on Random Access If eof is true, it must be cleared before seekg or seekp : gradeFile.clear(); // go to the beginning of the file gradeFile.seekg(0L, std::ios::beg);

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Random Access Information tellg member function: return current byte position in input file long int whereAmIreading; whereAmIreading = inData.tellg(); tellp member function: return current byte position in output file long int whereAmIwriting; whereAmIwriting = outData.tellp();

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved Opening a File for Both Input and Output

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley 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", std::ios::in | std::ios::out); Can also use std::ios::binary flag for binary data If replacing data record in file, it must be the same number of bytes

Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. End of Chapter 12