Topics Input and Output Streams More Detailed Error Testing

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Advertisements

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.
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.
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.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 13: Advanced File.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
COIT29222-Structured Programming Lecture Week 12  Reading: Textbook (4 th Ed.), Chapter 14 Textbook (6 th Ed.), Chapter 17 Study Guide Book 3, Module.
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC.
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.
FILE HANDLING IN C++.
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.
File handling in C++ BCA Sem III K.I.R.A.S. Using Input/Output Files Files in C++ are interpreted as a sequence of bytes stored on some storage media.
 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.
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.
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.
File Handling. Read data from file and display it on screen #include int main() { /* fin object is created with parameterzied constructor */ ifstream.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 1 due Friday, 7pm. RAD due next Friday. Presentations week 6. Today: –More details on functions,
1 CSC241: Object Oriented Programming Lecture No 32.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
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.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Learners Support Publications Working with Files.
Lecture 14 Arguments, Classes and Files. Arguments.
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.
Data File Handling in C++ Data File Handling in C++ Paritosh Srivastava PGT (Comp. Science) Kendriya VidyalayaJoshimath.
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.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
Programming with ANSI C ++
17 File Processing.
Chapter 13: Advanced File and I/O Operations
Data File Handling in C++
C ++ MULTIPLE CHOICE QUESTION
Basic Input and Output Operations
CISC/CMPE320 - Prof. McLeod
CPSC 231 D.H. C++ File Processing
FILE HANDLING IN C++.
File I/O.
Lecture 5A File processing Richard Gesick.
17 File Processing.
files Dr. Bhargavi Goswami Department of Computer Science
Today’s Lecture I/O Streams Tools for File I/O
Chapter 13: Advanced File and I/O Operations
C++ FileIO pepper.
Chapter 12: Advanced File Operations.
C++ Programming: chapter 6 – iostream
Data File Handling RITIKA SHARMA.
Presentation transcript:

Topics Input and Output Streams More Detailed Error Testing Member Functions for Reading and Writing Files Binary Files Creating Records with Structures Random-Access Files Opening a File for Both Input and Output

Input and Output Streams Input Stream – data stream from which information can be read Ex: cin and the keyboard Use istream, ifstream, and istringstream objects to read data Output Stream – data stream to which information can be written Ex: cout and monitor screen Use ostream, ofstream, and ostringstream objects to write data Input/Output Stream – data stream that can be both read from and written to Use fstream objects here

File Stream Classes ifstream (open primarily for input), ofstream (open primarily for output), and fstream (open for either or both input and output) All have open member function to connect the program to an external file All have close member function to disconnect program from an external file when access is finished Files should be open for as short a time as possible Always close files before the program ends See pr13-01.cpp

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);

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 See pr13-02.cpp

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);

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 flag File modes can be combined and passed as second argument of open member function See pr13-01.cpp

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

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);

Default File Open Modes ofstream: open for output only file cannot be read from file is created if no file exists file contents erased if file exists ifstream: open for input only file cannot be written to open fails if the file does not exist

More Detailed Error Testing Stream objects 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

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

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 See pr13-04.cpp

Detecting File Operation Errors The file handle is set to true if a file operation succeeds. It is set to false when a file operation fails Test the status of the stream by testing the file handle: inFile.open("myfile"); if (!inFile) { cout << "Can't open file"; exit(1); }

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 See pre13-05.cpp

getline Member Function getline(char s[ ], int max, char stop ='\n') char s[ ]: Character array to hold input int max : 1 more than the maximum number of characters to read char stop: Terminator to stop at if encountered before max number of characters is read . Optional, default is '\n' See pr13-06.cpp and pr13-07.cpp

Single Character Input get(char &ch) Read a single character from the input stream and put it in ch. Does not skip whitespace. ifstream inFile; char ch; inFile.open("myFile"); inFile.get(ch); cout << "Got " << ch; See pr13-08.cpp

Single Character Input, Again get() Read a single character from the input stream and return the character. Does not skip whitespace. ifstream inFile; char ch; inFile.open("myFile"); ch = inFile.get(); cout << "Got " << ch;

Single Character Output put(char ch) Output a character to a file Example ofstream outFile; outFile.open("myfile"); outFile.put('G');

Example of 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();

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

Rewinding a File To move to the 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(); See pr13-10.cpp

13.4 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

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)

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 <char *>

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((char*)(d),sizeof(d));

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( (char *)(data), 2*sizeof(double)); // only data[0] and data[1] contain // values See pr13-11.cpp

13.5 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

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<char*>(test1), sizeof(test1)); See pr13-12.cpp and pr13-13.cpp

13.6 Random-Access Files Sequential access: start at beginning of file and go through data the in file, in order, to the end of the file to access 100th entry in file, go through 99 preceding entries first Random access: access data in a file in any order can access 100th entry directly

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

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

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); See pr13-14.cpp and pr13-15.cpp

Random Access Information tellg member function: return current byte position in input file, as a long long whereAmI; whereAmI = inFile.tellg(); tellp member function: return current byte position in output file, as a long whereAmI = outFile.tellp(); See pr13-16.cpp

13.7 Opening a File for Both Input and Output A 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); See pr13-17.cpp, pr13-18.cpp, and pr13-19.cpp