Reading Data From and Writing Data To Text Files

Slides:



Advertisements
Similar presentations
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
Advertisements

1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
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.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Program Input and the Software Design Process ROBERT REAVES.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
1 CS 101 Lecture 2. 2 Input from the Keyboard Here is a program to accept input from the keyboard and put into into two variables. #include main(){ cout.
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.
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.
C++ Basics. Compilation What does compilation do? g++ hello.cpp g++ -o hello.cpp hello.
1 Simple File I/O Chapter 11 Switch Statement Chapter 12.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
1 Chapter 4 Program Input and the Software Design Process.
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.
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.
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.
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
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.
Chapter 14: Sequential Access Files
Basic concepts of C++ Presented by Prof. Satyajit De
ifstreams and ofstreams
Chapter Topics The Basics of a C++ Program Data Types
What Actions Do We Have Part 1
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
Basic Elements of C++.
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists File I/O Dr. Xiao Qin Auburn University.
Lab 7: File Input/Output Graham Northup
COMP 2710 Software Construction File I/O
Copyright © 2003 Pearson Education, Inc.
FILE INPUT OUTPUT Skill Area 315 Part B Materials Prepared by
Quiz Next Monday.
Data Streams.
Basic Elements of C++ Chapter 2.
File I/O.
Standard Input/Output Streams
Introduction to C++ Programming
Interactive I/O Input from keyboard Must prompt user User friendly
Basic File I/O and Stream Objects
Today’s Lecture I/O Streams Tools for File I/O
when need to keep permanently
Chapter 3: Input/Output
Introduction to cout / cin
Chapter 3 Input output.
CS150 Introduction to Computer Science 1
File I/O in C++ I.
CS150 Introduction to Computer Science 1
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
What Actions Do We Have Part 1
Reading from and Writing to Files
ifstreams and ofstreams
Introduction to cout / cin
Chapter 1 c++ structure C++ Input / Output
Lecture 3 More on Flow Control, More on Functions,
File I/O in C++ I.
getline() function with companion ignore()
Reading from and Writing to Files
Presentation transcript:

Reading Data From and Writing Data To Text Files Text File I/O Reading Data From and Writing Data To Text Files

#include <fstream> Text File I/O C++ Provides a File Stream library to read/write Text Files using syntax similar to cin/cout #include <fstream>

Text File I/O Text files must be Opened before they can be read from or written to, with a File Name specified. They should also be Closed after use.

Text File I/O #include <fstream> – defines the following: ofstream – data type used to declare a File Handle (variable) used to write to a Text File. ifstream – data type used to declare a File Handle (variable) used to read from a Text File.

ofstream Algorithm: To write data to a text file: - declare an ofstream file handle - (try to) open the file - if the file opened successfully, use the file handle exactly as cout is used. - close the file when done (forgetting this may result in lost data!)

ofstream #include <fstream> void main() { ofstream f; f.open(”mydata.txt”); if (!f.fail()) { f << ”Hello world ” << endl; f << setw(10) << 3.14159; f.close(); }

ofstream ofstream f; This declaration statement allocates a File Handle variable named f that can be used to write data to a file. Think of it as a “pipeline to a file”. Currently the “pipeline” is not connected to any file.

ofstream f.open(”mydata.txt”); This statement tries to open a file called ”mydata.txt” It may fail or succeed. If it succeeds, it “connects the pipeline” to the file.

THE CURRENT CONTENTS OF THE FILE! ofstream f.open(”mydata.txt”); If the file does not already exist, it will create a new file. If the file does already exist: IT WILL ERASE THE CURRENT CONTENTS OF THE FILE!

ofstream f.open(”mydata.txt”); Without a Path in the file name, it is assumed the file is in the Working Directory (Folder). Where is the Working Directory? It depends, usually: - the same folder as the executable (.exe) - when using the Debugger in MS-VS, in the same folder as the source (.cpp)

ofstream f.open(”mydata.txt”); Optionally, the complete path may be included in the file name: f.open( ”c:\\datafiles\\joiner\\mydata.txt”);

ofstream ”c:\\datafiles\\joiner\\mydata.txt” Why the double backslashes?!? Remember, for C++ string literals, a backslash is interpreted as “escape character coming up next”, and “\\” is interpreted as a SINGLE backslash. So the above C++ string literal actually means: c:\datafiles\joiner\mydata.txt

ofstream A string variable or constant may be used for the file name. string fn = ”c:\\files\\mydata.txt”; f.open(fn);

ofstream A string variable can be used to get the file name from the user: string fname; cout << ”Enter the file name: ”; cin >> fname; f.open(fname); But the user should NOT use \\ for \ (That silly escape character stuff is only for Programmers)

ofstream ofstream f( filename ); As a “shortcut”, a File Handle may be declared and opened with one statement: ofstream f (”mydata.txt”); is the same as: ofstream f; f.open(”mydata.txt”);

ofstream f.fail() It is possible that opening the file may fail for some reason (more likely with ifstream’s: see below). So the program should check every time .open() is used to ensure the file actually did open. The .fail() function returns true or false, and so may be used a conditional expression.

ofstream f.fail() Example f.open(”mydata.txt”); if (f.fail()) { cout << ”Failed to open file.\n”; return; // or do whatever the specs say }

ofstream f << Once the file is successfully open, use the File Handle the same as cout is used. Instead of printing on the screen, the text is written to the file. f << ”Fed Tax: ” << setw(10) << fedTax << endl;

ofstream f.close(); Once all data is written to the file, it should be closed. Failure to do so may mean the last characters inserted into to the file handle may not actually be written to the file (data is lost).

ofstream #include <fstream> void main() { ofstream f; f.open(”mydata.txt”); if (!f.fail()) { f << ”Hello world ” << endl; f << setw(10) << 3.14159; f.close(); }

ifstream Use ifstream as a Data Type to create a File Handle used to read data from a text file. Most syntax/issues of using ofstreams apply to using ifstreams. The main issue with ifstreams is not syntax/semantics, but is Algorithm Design

ifstream #include <fstream> void main() { ifstream f; string name; int age; float gpa; f.open(”mydata.txt”); if (!f.fail()) { f >> name >> age >> gpa; f.close(); }

ifstream f.open() .open() for ifstreams has the same issues as for ofstreams, with one exception: If the file does not exist, the .open() fails.

ifstream f >> Use the extraction operator on the file handle just as is used with cin. Differences with cin: - does NOT suspend the program to wait for the user (data is not coming from the keyboard!). - no prompts are needed (no human to ask!)

Design of Reading Files The Algorithm for reading a text file is dictated by the Format/Layout of the File.

Design of Reading Files See more in the in-class examples