© Janice Regan, CMPT 128, Jan 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.

Slides:



Advertisements
Similar presentations
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
Advertisements

Chapter 12 Streams and File I/O Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
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.
Computer Science 1620 Loops.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
Chapter 5: Loops and Files.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
C++ plus. 2 Goals Some general C++ tips 3 C++ Tips is header file for a library that defines three stream objects Keyboard an istream object named cin.
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.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Program Input and the Software Design Process ROBERT REAVES.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 12 Streams and File I/O Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
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,
Chapter 8 Data File Basics.
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
1 CS161 Introduction to Computer Science Topic #13.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
1 COMS 261 Computer Science I Title: String Class Date: October 3, 2005 Lecture Number: 14.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
Disk Files for I/O your variable (of type ifstream) your variable (of type ofstream) disk file “myInfile.dat” disk file “myOut.dat” executing program input.
Loops and Files. 5.1 The Increment and Decrement Operators.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Input/Output. Objectives In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
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.
Copyright © 2002 Pearson Education, Inc. Slide 1.
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.
Writing to Files and Reading From Files. Writing Data to a File Creating a new file, a.dat or.txt file #include #include // for file writing #include.
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.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
File I/O. Files allow permanent storage of programs and data. ifstream and ofstream objects –For file I/O the inclusion of is required. –Objects for file.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 File I/O.
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
Chapter 14: Sequential Access Files
What is wrong in the following function definition
C++ Basic Input and Output (I/O)
CS-103 COMPUTER PROGRAMMING
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists File I/O Dr. Xiao Qin Auburn University.
COMP 2710 Software Construction File I/O
Copyright © 2003 Pearson Education, Inc.
File I/O.
Lecture 5A File processing Richard Gesick.
File I/O.
Basic File I/O and Stream Objects
Today’s Lecture I/O Streams Tools for File I/O
Review of Strings which include file needs to be used for string manipulation? what using statement needs to be included for string manipulation? how is.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
File I/O in C++ I.
CS150 Introduction to Computer Science 1
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
Reading from and Writing to Files
Reading Data From and Writing Data To Text Files
COMS 261 Computer Science I
Lecture 3 More on Flow Control, More on Functions,
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors

© Janice Regan, CMPT Streams  Streams  Special objects  Deliver program input and output to/from your program  Think of a stream of output, cout  Think of a stream of input, cin  Think of << as an operator to move data from your program to an ouput stream  Think of >> as an operator to move data from an input stream into your program

© Janice Regan, CMPT Streams  A stream can be thought of as a flow of characters  An input stream flows into your program Can come from keyboard (cin) Can come from file  An output stream flows out of your program Can go to screen (cout, or cerr) Can go to file

© Janice Regan, CMPT Reading/Writing data (1)  Use iostream objects cin and cout  cin >> num;  Waits on-screen for keyboard entry  Value entered at keyboard is placed in the memory location reserved for variable num, that is the entered value is "assigned" to num

© Janice Regan, CMPT Reading/Writing data (2)  cout << num;  Value from the memory location reserved for variable num, is displayed on the screen  To remember direction of >> think of it as an arrow pointing to where the data is going cin >> num; //value is being put into variable num cout << num; //value in num is being sent to the screen

© Janice Regan, CMPT Error Output  Output with cerr  cerr works in the same way as cout  Two different streams of information cout and cerr  Both streams are displayed on the console (screen)  Can separate the two streams Display error information to the screen Redirect output to a file  Provides mechanism for distinguishing between regular output and error output.

© Janice Regan, CMPT Other Streams  The programmer can define other streams  Stream can flow into a file  Can have multiple streams each flowing into their own file  Streams can flow out of files  Can have multiple streams each flowing out of its own file  Programmer defined streams can be used like C++ defined streams cin, cout, and cerr  Each stream actually has more flexibility and functionality than we have discussed so far

© Janice Regan, CMPT File I/O Libraries  To access the objects and functions needed to use your own streams  You need the library fstream #include using namespace std;

© Janice Regan, CMPT Create a stream  First create a stream to read from  Declare a variable of type ifstream ifstream myInputStream;  OR a stream to write to  Declare a variable of type ofstream ofstream myOutputStream;  Types ifstream and ofstream are defined in library fstream

© Janice Regan, CMPT Connect your file to the stream  Once you have declared a variable to refer to the input or output stream then you need to connect your input or output file to that stream.  This process of connecting to the file is called “opening the file” myInputStream.open("infile.txt“); myOutputStream.open(“outfile.txt”);

© Janice Regan, CMPT File Names  The filenames "infile.txt“, “outfile.txt” used in the open statement refer to files that exist (for read or write) or will be created (for write) on your computers disk.  If input or output files are kept in the same folder as the executable then infile.txt and outfile.txt will be the actual names of the files  Otherwise infile.txt and outfile.txt must be paths to the files for example D:\CourseData\cmpt128\try123\infile.txt

© Janice Regan, CMPT Using files for input / output  Within C++ programs information is read from files or written to files  The file name (path) of the file saved on the computer’s disk for example infile.txt or outfile.txt is used only to connect to the stream you create in your program  All access to the file once it has been opened is done using the stream name for example myInputStream or myOutputStream

© Janice Regan, CMPT Reading data from a file  cin is an input stream  You have now declared and connected to your own input stream myInputStream  To read data from your input stream use myInputStream just like you used cin to read from the keyboard stream myInputStream >> variablename;

© Janice Regan, CMPT Writing data to a file  cout is an output stream  You have now declared and connected to your own output stream  To write data to this stream use myOutputStream just like you used cout myOutputStream << variablename;

© Janice Regan, CMPT Breaking the connection  When the program has completed reading from or writing to the file, the connection to the file is no longer needed.  The programmer needs to break the connection between the program and the file myInputStream.close(); myOutputStream.close();

© Janice Regan, CMPT Checking if the file opened  Sometimes we are unable to open a file  File does not exist, cannot be found  We cannot create the new file Disk is full Can not write where we asked to create the file  Need to check that the file was actually opened if ( myOutputStream.fail( ) )

© Janice Regan, CMPT Check: using function fail( )  Need to check that the file was actually opened myOutputStream.open(“infile.txt"); if ( myOutputStream.fail( ) ) { cout << "File open failed.\n"; exit(1); }

© Janice Regan, CMPT File Example: Simple File Input/Output (1) #include using namespace std; int main () { ifstream inStream; ofstream outStream; //declare variables and constants double meanValue = 0.0; double input1=0.0, input2 = 0.0; double input3 = 0.0, input4=0.0; inStream.open("inputFile"); if ( inStream.fail( ) ) { cerr << "inputFile not opened" << endl; return 1; } outStream.open("outputFile"); if ( outStream.fail( ) ) { cerr << "outputFile not opened" << endl; return 2; }

© Janice Regan, CMPT File Example: Simple File Input/Output (2) myInStream >> input1 >> input2 >> input3 >> input4; meanValue = (input1+input2+input3+input4)/4.0; myOutStream << "The mean of the first four input values is "; myOutStream << meanValue << endl; myInStream.close( ); myOutStream.close( ); Input FileOutput File The mean of the first four input values is 3.50

© Janice Regan, CMPT Formatting Output  We have seen how to format output on stream cout using manipulators  We can use the same manipulators to format on any output stream

© Janice Regan, CMPT Opening output files  When you open an output file using the C++ syntax we have discussed  You are able write information to the file  The information you write after you open the file will begin at the beginning of the file  If the output file does not exist it will be created  If the output file already exists when you open it, then the information you write will overwrite any information already in the file  What if you want to add information to the end of an existing file instead? The process of adding information to the end of the file is called appending information to the file

© Janice Regan, CMPT Appending to a File ofstream outStream; outStream.open("important.txt", ios::app);  If file doesn’t exist it will be created  If file already exists information will be added to the end of the existing file

© Janice Regan, CMPT Rereading from a file  If you want to reread the data in a file you can  Close the file, Clear any status saved from the last use of the file. Reopen the file. inStream.open("stuff.txt"); ⋮ inStream.close(); inStream.clear(); inStream.open("stuff.txt"); ⋮ inStream.close();

© Janice Regan, CMPT Checking End of File  In many situations we have an input file containing data with the following properties  Data for many sets of observations (e.g. name and age and student number for a series of students)  Data contains an unknown number of sets of observations  In these situations we often want to read and process each set of observations sequentially:  Read and process each set of observations  Begin with the first set in the file  Continue until the last set is processed  Done when the end of the file is reached  To implement solutions of this type we need to be able to test to see if we are at the end of the file

© Janice Regan, CMPT Endfile controlled Loop // Data is read from a file, one line (three values at a time // Each time a line is read the cost is updated // After all data is read the cost is printed to the screen ifstream infile; double v1,v2, v3, cost; infile.open(“filename”); // should check if file has been opened infile >> v1 >> v2 >> v3; while ( !infile.eof( ) ) // while not at the end of file { cost += (v1 + v2 / v3); infile >> v1 >> v2 >> v3; } infile.close( ); cout << “Total cost is “ << cost << endl;

© Janice Regan, CMPT Endfile controlled Loop T infile.eof( ) infile >> v1; Initial statement Loop condition F Statement 1; … Statement m; Update statement

© Janice Regan, CMPT // Data is read from a file, with one value on each line // Each time a line is read the cost is updated // After all data is read the cost is printed to the screen #include …. ifstream infile; infile.open("filename"); // should check if file has been opened while ( !infile.eof() ) { if( !( infile >> v1) && !infile.eof() ) { exit(1)} // exit if variable is not read cost += v1; } infile.close( ); cout << "Total cost is " << cost << endl; Check if variable was read

© Janice Regan, CMPT Buffered output (1)  When writing output to a file  Output is temporarily stored in an internal buffer  Output from multiple write statements may be stored in the same buffer  Output is only written to the screen when the buffer is full. Output is written one buffer at a time.  Closing the file causes the last partially full buffer to be written to the screen  What happens to the output buffer when the program stops due to an error?

© Janice Regan, CMPT Buffered output (2)  When a program stops for an error, the final partially full buffer may not be printed  When a program requires that output be displayed immediately (not buffered) outStream.flush();  Member function flush, for all output streams  All buffered output is written immediately

© Janice Regan, CMPT Return Value controlled Loop T infile >> v1 Loop condition F Statement 1; … Statement m;

Catching a character int main() { int numOne; cout "; while ( !(cin >> numOne) ) { cin.clear(); //clears the error flag cin.sync(); //removes remaining characters from the input stream //NEVER NEVER use cin.sync() if there is no data in the input stream cout << "You typed a character not an integer, Try again" << endl; } cout << "The integer you entered was: " << numOne <<endl; return 0; } © Janice Regan, CMPT