Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

Similar documents
Input and Output File (Files and Stream )

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Chapter 3 - Notes Input/Output

Chapter 14 Sequential Access Files

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

BITG 1113: Files and Stream LECTURE 10

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

Lecture 3 The character, string data Types Files

Fall 2017 CISC/CMPE320 9/27/2017

Lecture 5 Files and Streams

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapte t r r 9

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

I/O Streams and Standard I/O Devices (cont d.)

Week 5: Files and Streams

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 3: Input/Output

Lab # 02. Basic Elements of C++ _ Part1

C++ Input/Output Chapter 4 Topics

What we will learn about this week:

Simple File I/O.

Lab: Supplying Inputs to Programs

Chapter 12. Streams and File I/O

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Introduction. Lecture 5 Files and Streams FILE * FILE *

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

COMP322 - Introduction to C++

CHAPTER 3 BASIC INSTRUCTION OF C++

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

C++ Programming Lecture 10 File Processing

Name Section: M/W T/TH Number Definition Matching (8 Points)

Software Design & Programming I

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

Objects and streams and files CS427: Elements of Software Engineering

Chapter 12: Advanced File Operations

LECTURE 02 INTRODUCTION TO C++

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Chapter 5: Loops and Files

Name Section: M/W T/TH Number Definition Matching (6 Points)

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Scientific Computing

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CS2141 Software Development using C/C++ Stream I/O

UEE1303(1070) S 12 Object-Oriented Programming in C++

CPE Summer 2015 Exam I (150 pts) June 18, 2015

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Program Organization and Comments

C++ Structures Programming Workshop 2 (CSCI 1061U)

C++ Quick Guide. Advertisements

Developed By : Ms. K. M. Sanghavi

COMP322 - Introduction to C++

CS103L SPRING 2018 UNIT 7: FILE I/O

PROGRAMMING EXAMPLE: Checking Account Balance

The C++ Language. Arizona State University 1

Week 3: File I/O and Formatting 3.7 Formatting Output

System Design and Programming II

CSCI 1061U Programming Workshop 2. C++ Basics

Random File Access. 1. Random File Access

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Input/Output Streams: Customizing

Object Oriented Programming In C++

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Preview 8/28/2018. Review for COSC 120 (File Processing: Reading Data From a File)

Introduction to C ++

Unit-V File operations

Your First C++ Program. September 1, 2010

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

After going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file

File I/O CS 16: Solving Problems with Computers I Lecture #9

Advanced I/O Concepts

Chapter 1 INTRODUCTION

Lecture 14. Xiaoguang Wang. March 11th, 2014 STAT 598W. (STAT 598W) Lecture 14 1 / 36

1. Which of the following best describes the situation after Line 1 has been executed?

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

VuZs Team's Work. CS201 Spring Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May :52

120++: a C++ Subset Corresponding to A Project-Based Introduction to C++

C++ does not, as a part of the language, define how data are sent out and read into the program

Chapter 2. Procedural Programming

CSCE 206: Structured Programming in C++

I/O streams

A First Program - Greeting.cpp

CS2255 HOMEWORK #1 Fall 2012

File I/O Christian Schumacher, Info1 D-MAVT 2013

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

BITG 1233: Introduction to C++

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

Programming II with C++ (CSNB244) Lab 10. Topics: Files and Stream

Transcription:

Text File I/O We can use essentially the same techniques we ve been using to input from the keyboard and output to the screen and just apply them to files instead. If you want to prepare input data ahead, you may store the data in a file and direct the program to read its input from a file. If you want to save output data in a file to use later, you may direct the program to write data to a file. To read and/or write to a text file, perform the following steps: 1. Request the preprocessor to include file <fstream> as well as file <iostream>. The former contains the declarations for defining input and output streams other than cin and cout. 2. Declare an input stream to be of type ifstream or an output stream to be of type ofstream (or both). 3. Prepare the streams for use by using the function named open provided in file <fstream>. The parameter for function open is the external name of the file. The external name is the name under which the file is stored on the disk. 4. Put the file name to the left of the insertion or extraction operator. 5. When finished, use the close function to close the file. Here is an example program that reads four floating point data values from a file and writes them to another file in reverse order. #include <iostream> #include <fstream> using namespace std; float val1, val2, val3, val4; ofstream outdata; // declares 4 variables // declares input stream // declares output stream indata.open("data.in"); // binds program variable indata to file "Data.In" outdata.open("data.out"); // binds program variable outdata to file "Data.Out" indata >> val1 >> val2 >> val3 >> val4; outdata << val4 << endl; outdata << val3 << endl; outdata << val2 << endl; outdata << val1 << endl; outdata.close(); // inputs 4 values // outputs 4 values To reference a file in your program you need both an internal name and an external name. The internal name is what you call it in your program; the external name is the name the operating system knows it by. Somehow these two names must be associated with one

another. This association is called binding and is done in function open. Notice that indata and outdata are identifiers declared in your program; "Data.In" and "Data.Out" are character strings. Data.In is the name that was used when the input data file was created; Data.Out is the name of the file where the answers are stored. When the above program is run, if Data.In contains: 3.4 5.1 3.13145 55.23 then afterwards, a new file name Data.Out will be created that contains: 55.23 3.13145 5.1 3.4 Note that the filenames are case-sensitive on Unix systems. If an entire path is not declared, it is expected that the file is in the current working directory. In Visual Studio, this is in the main project folder, then in the sub-folder with the project name. If you specify the entire path to your file don t forget to use the double slashes to escape the file: myfile.open( c:\\my Documents\\In.txt ); C++11 allows you to use a literal string to avoid escaping the backslash: myfile.open(r"(c:\mydocs\in.txt)"); It is generally desirable to avoid putting in the full pathname. Instead, a relative pathname using the default folder is preferred. This is because a full pathname is normally unique to just your machine, so relying on this pathname will usually not work on someone else s computer. However, if the default folder is used, this will generally operate on anyone s computer. After opening the file, it s a very good idea to check to see if the open has failed. Upon failure the file variable will be equal to false. Failure could occur for many reasons (file not found, disk full, etc.) If successful, the file variable will be non-null: myfile.open( somefile.txt ); if (myfile) cout << Open succeeded ); else cout << Open failed ;

What if we didn t know in advance how many data items were in a file, and wanted to process it until we reached the end of the file? There is a function we can use to test for the end of the file, the eof() function. To test for the end of a file, use the variable name for the input stream, with the dotted notation: ifvar.eof(). This returns true if the end of the file has been reached, and false otherwise. The following example reads the file named test.txt and outputs it to the screen: string s; indata.open( test.txt ); while (!indata.eof()) getline(indata, s); cout << s << endl; // While not the end of the file // Read a line of text // Print it to the screen As long as we haven t reached the end of the file, we ll continue reading a line of text in and print it out to the screen. For most programs, instead of printing the data to the screen, you would be doing some other form of processing. This code can run differently on different operating systems! If you run this in Visual Studio on Windows and also in Unix, you ll notice an extra blank line printed in Unix. On a Unix system, the eof() call does not become true until we try to read past the end of the file. The program above actually reads past the end of the file and tries to print out the string s after we read the EOF marker. In this case we get a blank string when we try to use getline on the end of the file, so this program will always print a blank line at the end. If you don t want this behavior, the last line of the loop should be a getline. Another way to check to see if we ve reached the end of the file is to use the return value of getline(). This function will return NULL or false when it has reached the end of the file. This also works using cin >> var. This is generally the preferred method over using EOF. The result is we input from the file and check for the end of the file at the same time:

string s; indata.open( test.txt ); // Get a line of text and check for EOF at the same time while (getline(indata, s)) cout << s << endl; // Print it to the screen string s; indata.open( test.txt ); // Read a word at a time and output it until EOF while (indata >> s) cout << s << endl; // Print it to the screen Passing File Variables to Functions One final note about using file variables, if you wish to pass a file stream variable as a parameter in a function, the variable must be passed by reference. We have only covered the basics on file manipulation here. If you would like to know more (e.g. random access into files, appending to files, peeking into files, putting data back into file streams) then please refer to the textbook.

Binary File I/O To read and write files in binary we open them the same way, except use functions to read and write the file instead of the stream operators. There is a flag we append to the file to indicate we want to open it in binary. Here is an example that writes a double and an array of integers to a binary file. We can use the write function to save to a binary file. This function requires the first parameter be a char pointer, so we have to typecast to a (char *) from whatever data we are writing. The second parameter is the number of bytes to write. #include <iostream> #include <fstream> using namespace std; double d = 3.14; int x[] = 0, 1, 2, 15, 14; ofstream outfile; outfile.open("binary.dat", std::ios::binary); outfile.write((char *) &d, sizeof(double)); // put type into sizeof outfile.write(reinterpret_cast<char *>(x), 5 * sizeof(int)); // How many bytes to write. Reinterpret_cast is another way // to typecast at runtime to a char pointer. // We don t need &x since x is already a pointer. outfile.close(); This creates a binary file named binary.dat. If you try to open it with a text editor you will get garble. You could read it with a hex or binary file editor: 00000000 1F 85 EB 51 B8 1E 09 40 00 00 00 00 01 00 00 00 02 00 00 00 0F 00 00 00...Q...@... 00000018 0E 00 00 00 To read from the file we use the read function in a manner similar to the write function: #include <iostream> #include <fstream> using namespace std; double d = 0; int x[5];

ifstream infile; infile.open("binary.dat", std::ios::binary); infile.read((char *) &d, sizeof(double)); infile.read(reinterpret_cast<char *>(x), 5 * sizeof(int)); infile.close(); cout << "we read in: " << d << endl; for (int i = 0; i < 5; i++) cout << i << " " << x[i] << endl; This program outputs the data values stored from the first program. Binary has the advantage over text that it will generally take up less storage and makes it easy to write out large structures or arrays. It is generally more efficient than text. Text has the advantage of being easier to edit in file format.