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

Similar documents
C++ Programming Lecture 10 File Processing

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

Input and Output File (Files and Stream )

BITG 1113: Files and Stream LECTURE 10

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

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

Chapter 3 - Notes Input/Output

Chapte t r r 9

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

Unit-V File operations

Lecture 3 The character, string data Types Files

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

Chapter 3: Input/Output

C++ Input/Output Chapter 4 Topics

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

IS 0020 Program Design and Software Tools

Fall 2017 CISC/CMPE320 9/27/2017

Chapter 14 Sequential Access Files

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

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

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

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

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

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

Chapter-12 DATA FILE HANDLING

Objects and streams and files CS427: Elements of Software Engineering

C++ files and streams. Lec 28-31

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

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

C++ Input/Output: Streams

Object Oriented Programming In C++

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

Developed By : Ms. K. M. Sanghavi

Week 5: Files and Streams

Files Total: // Files Example 1. #include <iostream> #include <fstream>

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

System Design and Programming II

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

Lecture 9. Introduction

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

Fundamental File Processing Operations 2. Fundamental File Processing Operations

Streams contd. Text: Chapter12, Big C++

COMP322 - Introduction to C++

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

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

ios ifstream fstream

Advanced I/O Concepts

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

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

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

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

SHORT REVIEW OF CS TOPICS RANDOM NUMBERS (2 MARKS) which generates a random number in the range of 0 to n-1. For example;

EP241 Computing Programming

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

Input/Output Streams: Customizing

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

C++ Quick Guide. Advertisements

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

Chapter 12: Advanced File Operations

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

Chapter 8 File Processing

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

by Pearson Education, Inc. All Rights Reserved. 2

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

Fundamentals of Programming Session 27

COMP322 - Introduction to C++

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

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010

Fundamentals of Programming Session 25

A SHORT COURSE ON C++

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

Chapter 11 Customizing I/O

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

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

I/O streams

PROGRAMMING EXAMPLE: Checking Account Balance

Class Example. student.h file: Declaration of the student template. #ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED

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

Study Material for Class XII. Data File Handling

We will exclusively use streams for input and output of data. Intro Programming in C++

File handling Basics. Lecture 7

Lecture 5 Files and Streams

for (int i = 1; i <= 3; i++) { do { cout << "Enter a positive integer: "; cin >> n;

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

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

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

Software Design & Programming I

AC55/AT55 OBJECT ORIENTED PROGRAMMING WITH C++ DEC 2013

C++ How to Program 14.6

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

C++ STREAMS; INHERITANCE AS

Streams. Rupesh Nasre.

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

This can be thrown by dynamic_cast. This is useful device to handle unexpected exceptions in a C++ program

DISK FILE PROGRAM. ios. ofstream

Introduction to C++ (Extensions to C)

Module C++ I/O System Basics

Chapter 11 Customizing I/O

Introduction. Lecture 5 Files and Streams FILE * FILE *

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

Transcription:

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

LEARNING OBJECTIVES Upon completion, you should be able to: o define C++ text files o explain the benefits of using I/O file processing o explain the relationship of I/O files to the computer memory (volatile and non- volatile) o implement skills required for reading data from and writing results to text files in C++

TEXT FILE OVERVIEW 4.1 INTRODUCTION TO TEXT FILE 4.2 FILE OPERATIONS 4.3 FILE PROCESSING (File-array/record)

Overview of Part 1 Introduction to SIX (6) Steps: o Include header file fstream o Declare file object ofstream/ifstream o Open file o Check input file exists o Perform operation o Close file 4

Introduction to File File: area in secondary storage to hold info Is permanent Ideal for voluminous data Can be used to provide input data to a program or receive output data from a program, or both should reside in project directory for easy access Must be opened before it is used 5

File types Sequential Access File The information is accessed sequentially Random Files The information is accessed consecutive or in random order. Types Binary Files The information is accessed by its byte location in the file

Sequential Access Files o Often referred to as a text file. o Getting information from a file is referred to as reading the file. o Sending information to a file is referred to as writing to a file. o Files to which information is written are called output files. o files that are read by the computer are called input files. o Before a file can be written to or read from, it must be created and opened..

Classes ofstream Stream class to write on files or to create an output file. ifstream Stream class to read from files or to create an input file. fstream Stream class to both read and write from/to files 8

o ios is the base class. o istream and ostream inherit from ios o ifstream inherits from istream (and ios) o ofstream inherits from ostream (and ios) o iostream inherits from istream and ostream (& ios) o fstream inherits from ifstream, iostream, and ofstream www.themegallery.com LOGO

File Open Modes Mode Description ios::in Opens a file for input. ios::out Opens a file for output. ios::app Appends all output to the end of the file. ios::ate Opens a file for output. If the file already exists, move to the end of the file. Data can be written anywhere in the file. ios::truct ios::trunc Discards the file s contents if the file already exists. (This is the default action for ios:out). ios::binary Opens a file for binary input and output. 10

File I/O is a five-step processes: Introduction to File 1. Include fstream header #include <fstream> 2. Declare file stream variables Variable for the input (file) stream ifstream indata; Variable for the output (file) stream ofstream outdata; 3. Open file indata.open(directoryinputfile); outdata.open(directoryoutputfile); 4. Perform operation indata.getline(name, 20); //Reading Name from file outdata << Name; //Writing Name into file 5. Close the files It s not necessary to close the file but it s good practice indata.close(); outdata.close(); 11

Overview of Part 2 File Operations: o Write data into file o Read data from file o Display data from file to console 12

WRITE DATA INTO FILE The ofstream : is used to write primitive data type values, arrays, strings, and objects to a text file. Eg: The program creates an instance of ofstream and writes two lines to the file scores.txt. Each line consists of first name (a string), middle name initial (a character), last name (a string), and score (an integer). output << John << << T << Smith << << 90 << endl; scores.txt file John T Smith 90 Eric K Jones 55 output << Eric << << K << Jones << << 55 << endl; 13

WRITE DATA INTO FILE(A Complete Program) o Example 1: 14

WRITE DATA INTO FILE(A Complete Program) o Example 1 (output): 15

//Step1: Include a header file #include <fstream> WRITE DATA INTO FILE (A Complete Program) main(){ //Step 2: Declare an output stream variable ofstream outfile; //Step 3: Open for an output file outfile.open("score.txt"); AFTER run cout << "Press any key to continue..."; //Step 4: Write data into an output file outfile << "Robert" << " " << "J" << " " << "Column" << " " << 93 << endl; //Step 5: Close an output file outfile.close(); outfile << "Julia" << " " << "C" << " " << "Bradley" << " " << 78 << endl; CANNOT write in a file. WHY? } 16

WRITE DATA INTO FILE(More Examples) o Example 3: Write a statement Hello World 10 times into fout.txt file 17

WRITE DATA INTO FILE(More Examples) o Example 3 (output): 18

WRITE DATA INTO FILE Example 4: Write a program to store marks of students test. Append data to the file. To add the output at the end of an existing file, add statement ios::app

Checkpoint 1 i. Read degrees in Fahrenheit within 12 months. Then, convert into degrees in Celsius based on the following formula : Celcius = 5.0/9.0(Fahrenheit-32.0) ii. Write and store the information above to a specified file name as temperature.txt. iii. The information must be store in the output file according to the following format: 20

Checkpoint 1 //Step1: Include a header file #include <fstream> main(){ //Step 2: Declare an output stream variable ofstream outfile; float celcius, fahrenheit; //Step 3: Open for an output file outfile.open( temperature.txt"); } //Step 4: Write data into an output file //Step 5: Close an output file outfile.close(); 21

Checkpoint 1 main(){ : //Step 4: Write data into an output file outfile << "Fahrenheit" << setw(10) << "Celcius" << endl; outfile << "-*-*-*-*-*-" << setw(10) << "-*-*-*-*- ; cout << \nenter degrees in Fahrenheit within 12 months"; cout << \n-*-*-*-*--*-*-*-*--*-*-*-*--*-*-*-*--*-*-*-" << endl << endl; for(int i=0; i<12; i++){ cout << "Month " << (i+1) << ". "; cin >> fahrenheit; } } celcius = 5.0/9.0*(fahrenheit-32.0); outfile << setiosflags(ios::fixed) << setprecision(2) << setw(7) << fahrenheit << setw(12) << celcius << endl; 22

Create an input file Example:- create an input file to store numbers, that will be used in a particular program. 1. Use any text editor, for example notepad, MS Visual C++, etc. 2. Key in data, for example: 10 20 30 40 3. Save the file: example: num.dat or num.txt 23

Example of input file 24

READ DATA FROM FILE The ifstream : is used to read primitive data type values, arrays, strings, and objects from a text file. Eg: The program creates an instance of ifstream and reads all lines from the file testmarks.txt. Each line consists of name (a string), test 1 and test 2 (an integer) can be displayed on the screen. infile.getline(names, 25, ';') infile >> test1 >> test2; After INPUT from file 25

READ DATA FROM FILE (A Complete Program) #include <fstream.h> //Step1: Include a header file main(){ //Step 2: Declare an input stream variable ifstream infile; char names[25]; double test1, test2; //Step 3: Open for an input file infile.open( testmarks.txt ); Use getline() function to read character with spaces: ifstreamvariablename.getline(attributevariable, charactersize, delimiter); } //Step 4: Read data from an input file - using eof() infile.getline(names,25, ';'); infile >> test1 >> test2; while(!infile.eof()){ If not at end of file, continue reading data cout << names << " " << test1 << " " << test2; infile.getline(names,25, ';'); infile >> test1 >> test2; } infile.close(); //Step 5: Close an input file getch(); 26

READ DATA FROM FILE (A Complete Program) #include <fstream.h> //Step1: Include a header file main(){ //Step 2: Declare an input stream variable //Step 3: Open for an input file } if(!infile) To test if the file is not exist / not the file name { cout << Error: File could not be opened! << endl; } else { //Step 4: Read data from an input file - using eof() //Step 5: Close an input file } getch(); 27

READ DATA FROM FILE :Example of source code Output In current folder, the input file is exist 28

READ DATA FROM FILE: Example of source code Output In current folder, the input file does not exist 29

Read and write Text Files Write a program to copy data from a file named temp.txt into another file named copytemp.txt. 30

Read and write Text Files Write a program to copy data from a file named temp.txt into another file named copytemp.txt. //Step1: Include a header file #include <fstream> main(){ //Step 2: Declare an input/output stream variables ifstream infile; ofstream outfile; float celcius, fahrenheit; //Step 3: Open for an input/output files infile.open( temp.txt"); outfile.open( copytemp.txt"); //Step 4: Check input file exists or not //Step 5: Read data from an input file //Step 6: Write data into an output file //Step 5: Close both of the input and output files infile.close(); outfile.close(); } 31

Read and write Text Files main(){ : //Step 4: Check input file exists or not if(!infile) cout << "Error: File doesn't exist!" << endl; else { //Do Step 5 and Step 6 outfile << "These data are copied from other external file..." << endl; outfile << "Fahrenheit" << setw(10) << "Celcius" << endl; infile >> fahrenheit; infile >> celcius; while(!infile.eof()){ outfile << setiosflags(ios::fixed) << setprecision(2) << setw(7) << fahrenheit << setw(12) << celcius << endl; infile >> fahrenheit >> celcius; } cout << "No data remained..." << endl; } 32 }

Checkpoint 2 i. Read three tests (90, 80, and 70) that have been stored in a file named test.txt as follows: ii. Calculate an average of the three test. Write and store the result into a file known as testavg.txt, based on the following format: 33

Checkpoint 2 //Step1: Include a header file #include <fstream.h> main(){ //Step 2: Declare an input/output stream variables ifstream infile; ofstream outfile; char studentid[15]; int test1, test2, test3; float average; //Step 3: Open for an input/output files infile.open( test.txt"); outfile.open( testavg.txt"); //Step 4: Check input file exists or not //Step 5: Read data from an input file //Step 6: Write data into an output file //Step 5: Close an input/output files infile.close(); outfile.close(); } 34

Checkpoint 2 main(){ : //Step 4: Check input file exists or not if(!infile) cout << "Error: File doesn't exist!" << endl; else { //Do Step 5 and Step 6 cout << "Processing data..."<<endl; cout << "Press any key to continue..." << endl; } } infile >> studentid; outfile << "Student Id: " << studentid << endl; infile >> test1 >> test2 >> test3; average = (test1 + test2 + test3)/3.0; outfile << setiosflags(ios::fixed) << setprecision(2) << "Average test score: " << setw(6) << average; 35

Put( ) Function Invoke the put function on an output file variable to write a character: ofstream outfile; char x; int numgrade; outfile.open("fwrite.txt", ios::trunc ios::out); cout << "How many grade that you want to enter: "; cin >> numgrade; cout << "Enter " << numgrade << " grade(s):" << endl; cout << setw(17) << setfill('-') << endl; cout << setfill(' '); for(int i=0; i<numgrade; i++){ cout << "Grade " << (i+1) << ": "; cin >> x; outfile.put(x) << endl; } outfile.close(); Deletes all previous content in the file Similar to outfile << x; 36

Get( ) Function Invoke the get function on an input file variable to read a character. ifstream infile; infile.open("fwrite.txt", ios::in); cout << "Re-list the " << numgrade << " grades entered:" << endl; cout << setw(29) << setfill('-') << endl; cout << setfill(' '); infile.get(x); while(!infile.eof()){ cout << " " << x; infile.get(x); Similar to infile >> x; } infile.close(); 37

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

TEXT FILE OVERVIEW 4.1 INTRODUCTION TO TEXT FILE 4.2 FILE OPERATIONS 4.3 FILE PROCESSING (File-array/record)

CHAPTER 4.3 FILE PROCESSING (FILE-ARRAY / RECORD) Read data from file and store into array Read data as Record Pass file variable into function as parameter

READ DATA FROM FILE & STORE INTO ARRAY o Example 1: Suppose that a file names indata.txt contains the following data: 10.20 5.35 15.60 8.20 16.12 7.28 o The numbers in each line represents the length and width of a rectangle. Write C++ statements that will read data from indata.txt file and store into array rectangle[3][2]. Lastly, display the array onto the screen as the following format:

o Example 1: READ DATA FROM FILE & STORE INTO ARRAY

READ DATA FROM FILE & STORE INTO ARRAY o Example 1:

o Example 1 (Output): READ DATA FROM FILE & STORE INTO ARRAY Notepad : Console (Command Prompt):

READ DATA FROM FILE & STORE INTO ARRAY o Example 2: Extend from the same program, calculate the area of rectangle by reading the data in each line and store the results in outdata.txt.

o Example 2: READ DATA FROM FILE & STORE INTO ARRAY

o Example 2 (Output): READ DATA FROM FILE & STORE INTO ARRAY Notepad : Notepad :

o Example 3: READ DATA AS RECORD i. Read all the records that have been stored in a file named compstock.txt which consist of: brand, price and operating system. Notepad :

READ DATA AS RECORD o Example 3: ii. All the data will be stored into a variable struct array named computers. Given the definition of Computer record and declaration of computers array: struct Computer { char brand[20]; double price; int operating //1: Windows 8 //2: Windows 10 }; main() { Computer computers[7]; : }

o Example 3: READ DATA AS RECORD

o Example 3: READ DATA AS RECORD

READ DATA AS RECORD o Example 3 (output): Notepad : Console (Command Prompt):

o Example 4: PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER) o Based on the previous program, write a program by using modular programming techniques that find and write all brands of computers using Windows 10 and the total numbers of those computers in an output file named win10.txt. Console (Command Prompt): Notepad:

o Example 4: PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER)

o Example 4: PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER)

PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER) o Example 4:

o Example 4: PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER)

Binary I/O Although it is not technically precise and correct, you can envision: a) a text file as consisting of a sequence of characters and b) a binary file as consisting of a sequence of bits. For example: a) The decimal integer 199 is stored as the sequence of three characters, '1', '9', '9 (in a text file) b) the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals hex C7 (199 = 12 * 16 + 7). 58

Text vs. Binary I/O Computers do not differentiate binary files and text files. All files are stored in binary format, and thus all files are essentially binary files. Text I/O is built upon binary I/O to provide a level of abstraction for character encoding and decoding. 59

Text file vs Binary file o Both types of files store data in a sequence of bits. o The different between these two types of file is the way it is translated by the software to read or write the file. 60

Text file vs Binary file o A text file consists of data in the form of a sequence of characters, which it is written in characters and read also in the form of characters. o o As the data in memory is in the form of bits, so when the data in this memory to be written into a text file, C++ first translates (according to the character coding standard) in the form of characters before writing it into the text file. o Similarly, during the process of reading text files, data in the form of characters from a text file to be translated back to the form of bits, then sent to memory. 61

Text file vs Binary file o A binary file consists of data in the form of a sequence of bits, the data in binary files read and written in the form of a sequence of 1 and 0. o As we know, all the data stored in the program are stored in computer memory in the form of bits. o o When the data from this memory to be written into the binary file, it will be written directly into the binary file, bit by bit, as is the case in memory. o And, when data from this binary file to be read, the data bits in a binary file to be read one by one and sent directly to memory. 62

Advantage of text files o The advantage is a text file can be opened and edited using any software 'Text Editor'. o An example - Notepad. o Notepad can open text files. o the text file is more independent platform (platform independent) compared to a binary file. o This is because, a text file written in the form of characters in accordance with standard coding systems such as ASCII and Unicode. o So, it can be understood by all computers and software systems that use the same coding system. 63

Disadvantage binary files o A binary file can only be read or written using the software to write and read the file only. o If we write our program data in a binary file, then the data files can only be read and written using our program only. o If we try to open a binary file using other software or program, most likely it will be read and written in the wrong way, and can cause damage to the binary file. o For example, if we try to open a binary file using Notepad, what we can see is a group of characters that can not be understood, because Notepad has translated the binary files in the wrong way. 64

Disadvantage binary files o While binary files are unlikely to be translated correctly by the different computer or software system. o This is because some types of data bits written in a different order according to the computer. o For example, an integer may be written in 16 bits on some computers, and 32-bit on some other computer. o So, the integer data types written by a computer may be misinterpreted by the computer from the other types. 65

#include<iostream> #include<fstream> Example Struct studenttype { char firstname[15]; char lastname[15]; int ID; }; void main() { int studentids[5]={111111,222222,333333,444444,555555}; studenttype newstudent={ John, Wilson,777777}; ofstream outfile; outfile.open( ids.dat,ios::binary); outfile.write(reinterpret_cast< const char *>(studentids), sizeof(studentids)); outfile.write(reinterpret_cast<const char*>(&newstudent),sizeof(newstudent)); outfile.close();

ifstream infile; int arrayid[5]; studenttype student; Example infile.open( ids.dat ); if (!infile) { cout<< The input file does not exist. << The program terminates!!!! <<endl; return 1; } infile.read(reinterpret_cast< const char *>(arrayid),sizeof(arrayid)); for(int i=0;i<5;i++) cout<<arrayid[i]<< ; cout<<endl; } infile.read(reinterpret_cast<const char *>(&student),sizeof(student)); cout<<student.id<< <<student.firstname << <<student.lastname<<endl; infile.close();

CSC 138 Structured Programming END OF CHAPTER 4