C++ files and streams. Lec 28-31

Similar documents
Chapter 12 File Operations. Starting Out with C++, 3 rd Edition

System Design and Programming II

File handling Basics. Lecture 7

Advanced File Operations. Review of Files. Declaration Opening Using Closing. CS SJAllan Chapter 12 2

Developed By : Ms. K. M. Sanghavi

C++ Programming Lecture 10 File Processing

Files and Streams. 1 P a g e

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

More File IO. CIS 15 : Spring 2007

Unit-V File operations

Chapter-12 DATA FILE HANDLING

IS 0020 Program Design and Software Tools

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

Random File Access. 1. Random File Access

Object Oriented Programming Using C++ UNIT-3 I/O Streams

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

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

Lecture 9. Introduction

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

Chapte t r r 9

by Pearson Education, Inc. All Rights Reserved. 2

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

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

Object Oriented Programming In C++

Streams contd. Text: Chapter12, Big C++

Fundamentals of Programming Session 27

Study Material for Class XII. Data File Handling

BITG 1113: Files and Stream LECTURE 10

Chapter 14 Sequential Access Files

Chapter 8 File Processing

Chapter 12: Advanced File Operations

Fall 2017 CISC/CMPE320 9/27/2017

Input and Output File (Files and Stream )

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7. Data File Handling

Consider the following example where a base class has been derived by other two classes:

Fundamental File Processing Operations 2. Fundamental File Processing Operations

Writing a Good Program. 7. Stream I/O

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

All About: File I/O in C++ By Ilia Yordanov, ; C++ Resources

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

ios ifstream fstream

Advanced I/O Concepts

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING

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

Computer programs are associated to work with files as it helps in storing data & information permanently. File - itself a bunch of bytes stored on

Lecture 5 Files and Streams

Module 11 The C++ I/O System

Object Oriented Programming CS250

Streams in C++ Stream concept. Reference information. Stream type declarations

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

Introduction. Lecture 5 Files and Streams FILE * FILE *

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

DATA FILE HANDLING FILES. characters (ASCII Code) sequence of bytes, i.e. 0 s & 1 s

by Pearson Education, Inc. All Rights Reserved. 2

Case Study: High Adventure Travel Agency Part 3

C++ How to Program 14.6

MANAGING FILES OF RECORDS

Fundamentals of Programming Session 28

UNIT V FILE HANDLING

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

Downloaded from

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

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions

Object Oriented Programming

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...

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

Fig: iostream class hierarchy

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

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Lecture 3 The character, string data Types Files

Streams. Rupesh Nasre.

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

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

Software Design & Programming I

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

Streams - Object input and output in C++

Generate error the C++ way

Strings and Stream I/O

And Even More and More C++ Fundamentals of Computer Science

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

Page 1

Week 5: Files and Streams

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

by Pearson Education, Inc. All Rights Reserved. 2

C++ Input/Output Chapter 4 Topics

CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O

Objects and streams and files CS427: Elements of Software Engineering

Simple File I/O.

ENGI 1020 Introduction to Computer Programming R E Z A S H A H I D I J U L Y 2 6,

CS 103 Unit 14 - Streams

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

COMP322 - Introduction to C++

EP241 Computing Programming

10/23/02 21:20:33 IO_Examples

========================GDS2_BIN2TXT_main.cpp============================================

Module C++ I/O System Basics

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Overview of Lecture. 1 Overloading I/O Operators. 2 Overloading << and >> for Fractions. 3 Formatted vs Unformatted Input

Developed By : Ms. K. M. Sanghavi

Transcription:

C++ files and streams Lec 28-31

Introduction So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively. To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.

Files A file is a collection on information, usually stored on a computer s disk. Information can be saved to files and then later reused. All files are assigned a name that is used for identification purposes by the operating system File Name and Extension File Contents and the user. MYPROG.BAS MENU.BAT INSTALL.DOC CRUNCH.EXE BOB.HTML 3DMODEL.JAVA INVENT.OBJ PROG1.PRJ ANSI.SYS README.TXT BASIC program DOS Batch File Documentation File Executable File HTML (Hypertext Markup Language) File Java program or applet Object File Borland C++ Project File System Device Driver Text File 3

Process of Using a File Using a file in a program is a simple three-step process The file must be opened. If the file does not yet exits, opening it means creating it. Information is then saved to the file, read from the file, or both. When the program is finished using the file, the file must be closed. 4

Contd 5

File Input/Output Before file I/O can be performed, a C++ program must be set up properly. File access requires the inclusion of fstream.h Before data can be written to or read from a file, the file must be opened. ifstream inputfile; inputfile.open( customer.dat ); 6

Example This program demonstrates the declaration of an fstream object and the opening of a file. 1. #include <iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { 6. fstream datafile; // Declare file stream object 7. char filename[81]; 8. cout << "Enter the name of a file you wish to open\n"; 9. cout << "or create: "; 10. cin.getline(filename, 81); 11. datafile.open(filename, ios::out); 12. cout << "The file " << filename << " was opened.\n"; Output: 13. return 0; 14. } Enter the name of a file you wish to open or create: mystuff.dat The file mystuff.dat was opened. 7

Opening a File at Declaration fstream datafile( names.dat, ios::in ios::out); This program demonstrates the opening of a file at the time the file stream object is declared. 1. #include <iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { 6. fstream datafile("names.dat", ios::in ios::out); 7. cout << "The file names.dat was opened.\n"; 8. return 0; 9. } Output: The file names.dat was opened. 8

Testing for Open Errors datafile.open( cust.dat, ios::in); if (!datafile) { cout << Error opening file.\n ; } datafile.open( cust.dat, ios::in); if (datafile.fail()) { cout << Error opening file.\n ; } 9

Closing a File A file should be closed when a program is finished using it. This program demonstrates the close function. 1. #include <iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { fstream datafile; Output: File was created successfully. Now closing the file. 6. datafile.open("testfile.txt", ios::out); 7. if (!datafile) 8. { } cout << "File open error!" << endl; return 0; 9. cout << "File was created successfully.\n"; 10. cout << "Now closing the file.\n"; 11. datafile.close(); 12. return 0; } 10

File Default Open Modes File Type ofstream Default Open Mode The file is opened for output only. (Information may be written to the file, but not read from the file.) If the file does not exist, it is created. If the file already exists, its contents are deleted (the file is truncated). ifstream The file is opened for input only. (Information may be read from the file, but not written to it.) The file s contents will be read from its beginning. If the file does not exist, the open function fails. 11

File Mode Flag Meaning File Mode Flags ios::app ios::ate ios::binary ios::in ios::nocreate ios::noreplace ios::out ios::trunc Append mode. If the file already exists, its contents are preserved and all output is written to the end of the file. By default, this flag causes the file to be created if it does not exist. If the file already exists, the program goes directly to the end of it. Output may be written anywhere in the file. Binary mode. When a file is opened in binary mode, information is written to or read from it in pure binary format. (The default mode is text.) Input mode. Information will be read from the file. If the file does not exist, it will not be created and the open function will fail. If the file does not already exist, this flag will cause the open function to fail. (The file will not be created.) If the file already exists, this flag will cause the open function to fail. (The existing file will not be opened.) Output mode. Information will be written to the file. By default, the file s contents will be deleted if it already exists. If the file already exists, its contents will be deleted (truncated). This is the default mode used by ios::out. 12

Write on file The stream insertion operator (<<) may be used to write information to a file. outputfile << I love C++ programming!

Example This program uses the << operator to write information to a file. 1. #include <iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { fstream datafile; 6. char line[81]; Output: File opened successfully. Now writing information to the file. Done. 7. datafile.open("demofile.txt", ios::out); 8. if (!datafile) 9. { cout << "File open error!" << endl; return 0; } 10. cout << "File opened successfully.\n"; 11. cout << "Now writing information to the file.\n"; 12. datafile << "Jones\n"; 13. datafile << "Smith\n"; 14. datafile.close(); 15. cout << "Done.\n"; return 0; } 14

Example This program writes information to a file, closes the file, then reopens it and appends more information. 1. #include <iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { fstream datafile; 6. datafile.open("demofile.txt", ios::out); 7. datafile << "Jones\n"; 8. datafile << "Smith\n"; 9. datafile.close(); 10. datafile.open("demofile.txt", ios::app); 11. datafile << "Willis\n"; 12. datafile << "Davis\n"; 13. datafile.close(); 14. return 0; } 15

Read from file The stream extraction operator (>>) may be used to read information from a file. 16

Example This program uses the >> operator to read information from a file. 1. #include <iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { fstream datafile; 6. char name[81]; Output: File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done. 7. datafile.open("demofile.txt", ios::in); 8. if (!datafile) 9. { cout << "File open error!" << endl; return 0; } 10. cout << "File opened successfully.\n"; 11. cout << "Now reading information from the file.\n"; 12. for (int count = 0; count < 4; count++) 13. { datafile >> name; cout << name << endl; } 14. datafile.close(); 15. cout << "Done.\n"; 16. return 0; } 17

Detecting the End of a File The eof() member function reports when the end of a file has been encountered. if (infile.eof()) infile.close(); In C++, end of file doesn t mean the program is at the last piece of information in the file, but beyond it. The eof() function returns true when there is no more information to be read. 18

Example This program uses the file stream object's eof() member function to detect the end of the file. 1. #include <iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { fstream datafile; 6. char name[81]; 7. datafile.open("demofile.txt", ios::in); 8. if (!datafile) Done. 9. { cout << "File open error!" << endl; return 0; } 10. cout << "File opened successfully.\n"; 11. cout << "Reading information from the file.\n"; 12. datafile >> name; // Read first name from the file 13. while (!datafile.eof()) 14. { cout << name << endl; 15. datafile >> name; } 16. datafile.close(); 17. cout << "\ndone.\n"; 18. return 0; } 19 File opened successfully. Reading information from the file. Jones Smith Willis Davis

Member Functions for Reading and Writing Files File stream objects have member functions for more specialized file reading and writing. 20

Example This program uses the file stream object's eof() member function to detect the end of the file. 1. #include <iostream> Output: 2. #include <fstream> Jones 3. using namespace std; Smith 4. int main() Willis 5. { fstream namefile; Davis 6. char input[81]; namefile.open("demofile.txt", ios::in); 7. if (!namefile) 8. { cout << "File open error!" << endl; return 0; } 9. namefile >> input; 10. while (!namefile.eof()) 11. { cout << input << endl; namefile >> input; } 12. namefile.close(); 13. return 0; 21

The getline Member Function datafile.getline(str, 81, \n ); str This is the name of a character array, or a pointer to a section of memory. The information read from the file will be stored here. 81 This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read. \n This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it s left our, \n is the default.) 22

Example This program uses the file stream object's getline member function to read a line of information from the file. Output: 1. #include <iostream> Jones 2. #include <fstream> Smith 3. using namespace std; 4. int main() Willis 5. { fstream namefile; Davis 6. char input[81]; namefile.open("demofile.txt", ios::in); 7. if (!namefile) 8. { cout << "File open error!" << endl; return 0; } 9. namefile.getline(input, 81); // use \n as a delimiter 10. while (!namefile.eof()) 11. { cout << input << endl; 12. namefile.getline(input, 81); // use \n as a delimiter } 13. namefile.close(); 14. return 0; } 23

The get Member Function This program asks the user for a file name. The file is opened and its contents are displayed on the screen. 1. #include <iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { fstream file; 6. char ch, filename[51]; 7. cout << "Enter a file name: "; 8. cin >> filename; 9. file.open(filename, ios::in); 10. if (!file) 11. { cout << filename << could not be opened.\n"; return 0; } 12. file.get(ch); // Get a character 13. while (!file.eof()) 14. { cout << ch; file.get(ch); // Get another character } 15. file.close(); 16. return 0; } 24

The put Member Function This program demonstrates the put member function. 1. #include <iostream> 2. #include <fstream> using namespace std; 3. int main() 4. { fstream datafile("sentence.txt", ios::out); 5. char ch; cout << "Type a sentence and be sure to end it with a "; 6. cout << "period.\n"; 7. while (1) 8. { cin.get(ch); 9. datafile.put(ch); 10. if (ch == '.') 11. break; 12. } 13. datafile.close(); 14. return 0; } Type a sentence and be sure to end it with a period. I am on my way. Resulting Contents of the File SENTENCE.TXT: I am on my way. Output: 25

Unformatted I/O with read and write read and write member functions Unformatted I/O Input/output raw bytes to or from a character array in memory Since the data is unformatted, the functions will not terminate at a newline character for example Instead, like getline, they continue to process a designated number of characters If fewer than the designated number of characters are read, then the failbit is set.

File pointers to read/write from binary files To write n bytes: write (const char* buffer, int n); To read n bytes (to a pre-allocated buffer): read (char* buffer, int num)

Example 1. #include<iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { int a[] = {10,23,3,7,9,11,25}; 6. fstream fs; 7. fs.open("myfile.txt", ios::binary ios::out); 8. fs.write((char*) &a, sizeof(a)); 9. fs.close(); 10. for(int i = 0; i < 7; i++) a[i] = 0; 11. fs.open("myfile.txt", ios::in ios::binary); 12. fs.read((char*) &a, sizeof(a)); 13. for(int i = 0; i < 7; i++) cout << a[i] << " "; 14. fs.close(); }

Random Access Files Random Access means non-sequentially accessing information in a file. 29

Mode Flags Mode Flag ios::beg ios::end ios::cur Description The offset is calculated from the beginning of the file. The offset is calculated from the end of the file. The offset is calculated from the current position. 30

Contd Statement File.seekp(32L, ios::beg); file.seekp(-10l, ios::end); file.seekp(120l, ios::cur); file.seekg(2l, ios::beg); file.seekg(-100l, ios::end); file.seekg(40l, ios::cur); file.seekg(0l, ios::end); How it Affects the Read/Write Position Sets the write position to the 33rd byte (byte 32) from the beginning of the file. Sets the write position to the 11th byte (byte 10) from the end of the file. Sets the write position to the 121st byte (byte 120) from the current position. Sets the read position to the 3rd byte (byte 2) from the beginning of the file. Sets the read position to the 101st byte (byte 100) from the end of the file. Sets the read position to the 41st byte (byte 40) from the current position. Sets the read position to the end of the 31 file.

File position pointers Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream ios::cur for positioning relative to the current position in a stream ios::end for positioning relative to the end of a stream.

Continued position to the nth byte of fileobject (assumes ios::beg) fileobject.seekg( n ); position n bytes forward in fileobject fileobject.seekg( n, ios::cur ); position n bytes back from end of fileobject fileobject.seekg( n, ios::end ); position at end of fileobject fileobject.seekg( 0, ios::end );

Example This program demonstrates the seekg function. 1. #include <iostream> 2. #include <fstream> 3. using namespace std; 4. int main() 5. { fstream file("demofile.txt", ios::in); 6. char ch; 7. file.seekg(5l, ios::beg); 8. file.get(ch); 9. cout << "Byte 5 from beginning: " << ch << endl; 10. file.seekg(-10l, ios::end); 11. file.get(ch); 12. cout << "Byte 10 from end: " << ch << endl; 13. file.seekg(3l, ios::cur); 14. file.get(ch); 15. cout << "Byte 3 from current: " << ch << endl; 16. file.close(); 17. return 0;} 34