CPS120: Introduction to Computer Science Lecture 15 B Data Files.

Slides:



Advertisements
Similar presentations
Files Used to transfer data to and from disk. Opening an Output File Stream #include // File stream library. ofstream outfile;// Declare file stream variable.
Advertisements

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.
File Input/Output. External Files Batch –Requires use of data files (save to disk) –Batch can be run during off peak use –allows things to be complete.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
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.
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 15.
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.
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.
Program Input and the Software Design Process ROBERT REAVES.
Chapter 3 Interactivity and Expressions CSC 125 Introduction to C++ programming.
© 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.
Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA
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.
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.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
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.
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.
Computer Programming TCP1224 Chapter 13 Sequential File Access.
CPS120: Introduction to Computer Science File Systems and Directories Nell Dale John Lewis.
C++ FILE I/O.
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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Loops and Files. 5.1 The Increment and Decrement Operators.
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.
Learners Support Publications Working with Files.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Lecture 14 Arguments, Classes and Files. Arguments.
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.
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.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.
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.
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Computer Programming II Lecture 9. Files Processing - We have been using the iostream standard library, which provides cin and cout methods for reading.
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 14: Sequential Access Files
Programming with ANSI C ++
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
CISC/CMPE320 - Prof. McLeod
Lecture 5A File processing Richard Gesick.
Topics Introduction to File Input and Output
Interactive I/O Input from keyboard Must prompt user User friendly
Text Files All the programs you've seen so far have one thing in common: Any data the program uses or calculates is lost when the program ends. In order.
Chapter 12: Advanced File Operations.
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
Reading from and Writing to Files
Topics Introduction to File Input and Output
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

CPS120: Introduction to Computer Science Lecture 15 B Data Files

Working with Data Files It is possible to have a C++ program read and use a data file that is stored on your PC's hard drive –Rarely does a program work without relatively large amounts of data. –Rather than requiring the user to input large amounts of data, one often "reads" data from an external data file.

Using External Files External data files are simply text files (usually with the extension.txt or.dat) that are stored in the same folder as the C++ program which access them. It is possible to have a C++ program read files that are stored anywhere else on your PC's hard drive or network –You will have to supply the path of those files in order to successfully access them.

Sequential Files Stores data as one long continuous piece of data Each different element is stored next to the prior piece of element There are no "empty bytes" of disk space in between consecutive pieces of data To access a specific record (piece of data), though, the C++ program must read through all of the former pieces of data

Random-Access Files A random-access external data file stores data into blocks of memory of equal size This may waste some disk space, it does speed up access times.

An Analogy Sequential-access data files compare to audio cassette tapes AS random-access data files compare to audio compact discs (CD's)

Opening and Closing Data Files Files must be officially be opened before they are used by a C++ program To open a sequential-access file, you must first declare a file pointer that you intend to point to the file that you will open

Required Compiler Directives Any program that uses file pointers must include the fstream.h header file with the compiler directive, #include at the top of the program

Preparing to Use Files Opening a sequential-access file ofstream outfile; –ofstream is a C++ keyword indicating the type of pointer that you created –outfile is simply the programmer's chosen name for the file pointer (and can be any valid name) Open the file "mydata.txt" that is stored on your PC's hard drive outfile.open("mydata.txt", ios::out); or the shorter version outfile.open("mydata.txt"); –output (out) is the default type of access for ofstream objects

Reading From a File Declare a file pointer as an ifstream object with: ifstream infile; –ifstream is a keyword and infile is the name for the file pointer. Open the actual file for reading with: infile.open("mydata.txt", ios::in); or the shorter version infile.open("mydata.txt");

Using Sequential Files A sequential access file cannot be opened for input and output at the same time You cn close a file that was opened for input and reopen it for output during a program's execution

Closing Files It is very important to always officially close a file, when you are finished using it from within a C++ program. The following statement would close the file, which is pointed to by the file pointer infile infile.close();

Preparing to Write Output It is wise to check to make sure that there wasn't an error actually opening the data file One can use an if statement like the following to protect the program from crashing. if (outfile) // same as if (outfile != 0) { outfile << "John Doe" << endl; } else { cout << "An error occurred while opening the file.\n"; }

Writing Output To write data to a sequential-access data file you would use a statement like: outfile << "John Doe" << endl; to print that name to the next line in the data file pointed to by the file pointer, outfile.

Reading Data From Files Use the insertion operator (>>). But, instead of using the cin keyword, you use the file pointer name that you declared. infile >> x; This statement stores the next numeric value in the file pointed to by the file pointer, infile, into the variable, x.

Appending Data Adding data to the end of a sequential-access data file is called appending Open the file using the ios::app stream operation mode as in: outfile.open("myfile.txt", ios::app); where the app is short for append. If you accidentally open the file with the ios::out mode, you will end up overwriting data in the file because C++ will write the first piece of outputted data at the beginning of the sequential-access data file

Detecting the End of a File. Use the eof function to determine whether the end of a sequential-access file has been reached. This function returns a 1 (true) if an attempt has been made to read past the end of the file. do { infile >> x; if ( !infile.eof( ) ) { cout << x << endl; } } while ( !infile.eof( ) );

Using Multiple Data Files For one C++ program to access multiple data files, you simply have to create multiple file pointers (each one pointing to a different data file). For example, infile.open("inputfile.txt"); outfile.open("outputfile.txt");

Sequential Read / Write One disadvantage to using sequential-access files is that it is tedious to insert data in the middle The common method is to open the file and read each line, one at a time. –As you read each line, you write the information into a new, blank file that is opened for output. –When you reach the point at which you wish to insert new information, you simply write that information to its proper place in the new, second file. –Then, continue to read each line from the first file and copy it to the second file

Prompting for File Names Using the c_str function with a string variable, you can ask the user to input the file to be opened and store that filename in a string variable. Then, you can open the file. For example, string fileName; // user's input ifstream infile; // the file for input cin >> fileName; // getting user's inputted filename infile.open(filename.c_str()); // opening the file for input

Standardized File Handling In order to standardize file handling, many modern operating systems include their own set of file handling functions that programmers can use. –Microsoft Windows programmers can use predefined funtions from the Microsoft Foundation Class library (MFC library), a C++ implementation of the Windows application programming interface (API).