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

Size: px
Start display at page:

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

Transcription

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

2 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++

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

4 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

5 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

6 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

7 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..

8 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

9 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 LOGO

10 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

11 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

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

13 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

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

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

16 //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

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

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

19 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

20 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

21 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

22 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

23 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: Save the file: example: num.dat or num.txt 23

24 Example of input file 24

25 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

26 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

27 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

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

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

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

31 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

32 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 }

33 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

34 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

35 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

36 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

37 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

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

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

40 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

41 READ DATA FROM FILE & STORE INTO ARRAY o Example 1: Suppose that a file names indata.txt contains the following data: 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:

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

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

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

45 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.

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

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

48 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 :

49 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]; : }

50 o Example 3: READ DATA AS RECORD

51 o Example 3: READ DATA AS RECORD

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

53 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:

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

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

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

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

58 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 * ). 58

59 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

60 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

61 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

62 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

63 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

64 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

65 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

66 #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();

67 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();

68 CSC 138 Structured Programming END OF CHAPTER 4

C++ Programming Lecture 10 File Processing

C++ Programming Lecture 10 File Processing C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential

More information

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

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents File I/O 1 File Names and Types A file name should reflect its contents Payroll.dat Students.txt Grades.txt A file s extension indicates the kind of data the file holds.dat,.txt general program input or

More information

Input and Output File (Files and Stream )

Input and Output File (Files and Stream ) Input and Output File (Files and Stream ) BITE 1513 Computer Game Programming Week 14 Scope Describe the fundamentals of input & output files. Use data files for input & output purposes. Files Normally,

More information

BITG 1113: Files and Stream LECTURE 10

BITG 1113: Files and Stream LECTURE 10 BITG 1113: Files and Stream LECTURE 10 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of input & output files. 2. Use data files for input & output

More information

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

Convenient way to deal large quantities of data. Store data permanently (until file is deleted). FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.

More information

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

Object Oriented Programming Using C++ UNIT-3 I/O Streams File - The information / data stored under a specific name on a storage device, is called a file. Stream - It refers to a sequence of bytes. Text file - It is a file that stores information in ASCII characters.

More information

Chapter 3 - Notes Input/Output

Chapter 3 - Notes Input/Output Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:

More information

Chapte t r r 9

Chapte t r r 9 Chapter 9 Session Objectives Stream Class Stream Class Hierarchy String I/O Character I/O Object I/O File Pointers and their manipulations Error handling in Files Command Line arguments OOPS WITH C++ Sahaj

More information

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

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() { 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,

More information

Unit-V File operations

Unit-V File operations Unit-V File operations What is stream? C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs. A C++ stream is a flow of data into or out of a program, such as the

More information

Lecture 3 The character, string data Types Files

Lecture 3 The character, string data Types Files Lecture 3 The character, string data Types Files The smallest integral data type Used for single characters: letters, digits, and special symbols Each character is enclosed in single quotes 'A', 'a', '0',

More information

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

Consider the following example where a base class has been derived by other two classes: Class : BCA 3rd Semester Course Code: BCA-S3-03 Course Title: Object Oriented Programming Concepts in C++ Unit IV Polymorphism The word polymorphism means having many forms. Typically, polymorphism occurs

More information

Chapter 3: Input/Output

Chapter 3: Input/Output Chapter 3: Input/Output I/O: sequence of bytes (stream of bytes) from source to destination Bytes are usually characters, unless program requires other types of information Stream: sequence of characters

More information

C++ Input/Output Chapter 4 Topics

C++ Input/Output Chapter 4 Topics Chapter 4 Topics Chapter 4 Program Input and the Software Design Process Input Statements to Read Values into a Program using >>, and functions get, ignore, getline Prompting for Interactive Input/Output

More information

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

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input Input and Output Outline Formatting outputs String data type Interactive inputs File manipulators CS 1410 Comp Sci with C++ Input and Output 1 CS 1410 Comp Sci with C++ Input and Output 2 No I/O is built

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical

More information

Fall 2017 CISC/CMPE320 9/27/2017

Fall 2017 CISC/CMPE320 9/27/2017 Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader

More information

Chapter 14 Sequential Access Files

Chapter 14 Sequential Access Files Chapter 14 Sequential Access Files Objectives Create file objects Open a sequential access file Determine whether a sequential access file was opened successfully Write data to a sequential access file

More information

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or 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. C++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++

More information

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

Streams in C++ Stream concept. Reference information. Stream type declarations Stream concept A stream represent a sequence of bytes arriving, being retrieved, being stored, or being sent, in order. A stream is continuos and offer sequential access to the data. Each byte can be read

More information

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

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay Input and Output Data Processing Course, I. Hrivnacova, IPN Orsay Output to the Screen Input from the Keyboard IO Headers Output to a File Input from a File Formatting I. Hrivnacova @ Data Processing Course

More information

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

I/O Streams and Standard I/O Devices (cont d.) 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 from the standard input device Learn how to use predefined

More information

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

Programming II with C++ (CSNB244) Lab 10. Topics: Files and Stream Topics: Files and Stream In this lab session, you will learn very basic and most common I/O operations required for C++ programming. The second part of this tutorial will teach you how to read and write

More information

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

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure Computer Systems Computer System Computer Structure C++ Environment Imperative vs. object-oriented programming in C++ Input / Output Primitive data types Software Banking System Compiler Music Player Text

More information

Chapter-12 DATA FILE HANDLING

Chapter-12 DATA FILE HANDLING Chapter-12 DATA FILE HANDLING Introduction: A file is a collection of related data stored in a particular area on the disk. Programs can be designed to perform the read and write operations on these files.

More information

Objects and streams and files CS427: Elements of Software Engineering

Objects and streams and files CS427: Elements of Software Engineering Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18 Today s topics 1 Recall...... Dynamic Memory Allocation...

More information

C++ files and streams. Lec 28-31

C++ files and streams. Lec 28-31 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

More information

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

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

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

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 16 Files 16.1 Introduction At times it is required to store data on hard disk or floppy disk in some application program. The data is stored in these devices using the concept of file. 16.2 Objectives

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:

More information

Object Oriented Programming In C++

Object Oriented Programming In C++ C++ Question Bank Page 1 Object Oriented Programming In C++ 1741059 to 1741065 Group F Date: 31 August, 2018 CIA 3 1. Briefly describe the various forms of get() function supported by the input stream.

More information

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

UEE1303(1070) S 12 Object-Oriented Programming in C++ Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member

More information

Developed By : Ms. K. M. Sanghavi

Developed By : Ms. K. M. Sanghavi Developed By : Ms. K. M. Sanghavi Designing Our Own Manipulators We can design our own manipulators for certain special purpose.the general form for creating a manipulator without any arguments is: ostream

More information

Week 5: Files and Streams

Week 5: Files and Streams CS319: Scientific Computing (with C++) Week 5: and Streams 9am, Tuesday, 12 February 2019 1 Labs and stuff 2 ifstream and ofstream close a file open a file Reading from the file 3 Portable Bitmap Format

More information

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

Files Total: // Files Example 1. #include <iostream> #include <fstream> Files // Files Example 1 datafile.open("datafile01.txt"); 61.7 86.36 78.12 Total: 261.43 // Prime the reading of the file. while(datafile) cout

More information

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

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file? CS162 External Data Files 1 External Files So far, all of our programs have used main memory to temporarily store

More information

System Design and Programming II

System Design and Programming II System Design and Programming II CSCI 194 Section 01 CRN: 10968 Fall 2017 David L. Sylvester, Sr., Assistant Professor Chapter 12 Advanced File Operation File Operations A file is a collection of data

More information

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

File Operations. Lecture 16 COP 3014 Spring April 18, 2018 File Operations Lecture 16 COP 3014 Spring 2018 April 18, 2018 Input/Ouput to and from files File input and file output is an essential in programming. Most software involves more than keyboard input and

More information

Lecture 9. Introduction

Lecture 9. Introduction Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of

More information

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

File I/O Christian Schumacher, Info1 D-MAVT 2013 File I/O Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Input and Output in C++ Stream objects Formatted output Writing and reading files References General Remarks I/O operations are essential

More information

Fundamental File Processing Operations 2. Fundamental File Processing Operations

Fundamental File Processing Operations 2. Fundamental File Processing Operations 2 Fundamental File Processing Operations Copyright 2004, Binnur Kurt Content Sample programs for file manipulation Physical files and logical files Opening and closing files Reading from files and writing

More information

Streams contd. Text: Chapter12, Big C++

Streams contd. Text: Chapter12, Big C++ Streams contd pm_jat@daiict.ac.in Text: Chapter12, Big C++ Streams Objects are Abstracted Wrapper around input/output source/destinations Steps in reading/writing streams- Open: Establish connection between

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 05 - I/O using the standard library & Introduction to Classes Milena Scaccia School of Computer Science McGill University February 1, 2011 Final note on

More information

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

C++ does not, as a part of the language, define how data are sent out and read into the program Input and Output C++ does not, as a part of the language, define how data are sent out and read into the program I/O implementation is hardware dependent The input and output (I/O) are handled by the standard

More information

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

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

ios ifstream fstream

ios ifstream fstream File handling in C++ In most of the real time programming problems we need to store the data permanently on some secondary storage device so that it can be used later. Whenever we have to store the data

More information

Advanced I/O Concepts

Advanced I/O Concepts Advanced Object Oriented Programming Advanced I/O Concepts Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1 Streams Diversity of input sources or output destinations

More information

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

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types. The C++ Language Input and Output Output! Output is information generated by a program.! Frequently sent the screen or a file.! An output stream is used to send information. Another type supplied by C++

More information

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

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

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

Week 3: File I/O and Formatting 3.7 Formatting Output Week 3: File I/O and Formatting 3.7 Formatting Output Formatting: the way a value is printed: Gaddis: 3.7, 3.8, 5.11 CS 1428 Fall 2014 Jill Seaman spacing decimal points, fractional values, number of digits

More information

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

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams Physics 6720 I/O Methods October 30, 2002 We have been using cin and cout to handle input from the keyboard and output to the screen. In these notes we discuss further useful capabilities of these standard

More information

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

SHORT REVIEW OF CS TOPICS RANDOM NUMBERS (2 MARKS) which generates a random number in the range of 0 to n-1. For example; SHORT REVIEW OF CS TOPICS RANDOM NUMBERS (2 MARKS) Generating Random Numbers The key function in generating random numbers is; int random (int n); which generates a random number in the range of 0 to n-1.

More information

EP241 Computing Programming

EP241 Computing Programming EP241 Computing Programming Topic 9 File Management Department of Engineering Physics University of Gaziantep Course web page www.gantep.edu.tr/~bingul/ep241 Sep 2013 Sayfa 1 Overview of Streams in C++

More information

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

CPE Summer 2015 Exam I (150 pts) June 18, 2015 Name Closed notes and book. If you have any questions ask them. Write clearly and make sure the case of a letter is clear (where applicable) since C++ is case sensitive. You can assume that there is one

More information

Input/Output Streams: Customizing

Input/Output Streams: Customizing DM560 Introduction to Programming in C++ Input/Output Streams: Customizing Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne Stroustrup]

More information

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

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

More information

C++ Quick Guide. Advertisements

C++ Quick Guide. Advertisements C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and

More information

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

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag

More information

Chapter 12: Advanced File Operations

Chapter 12: Advanced File Operations Chapter 12: Advanced File Operations 12.1 File Operations File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to files Used in many applications:

More information

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

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

Chapter 8 File Processing

Chapter 8 File Processing Chapter 8 File Processing Outline 1 Introduction 2 The Data Hierarchy 3 Files and Streams 4 Creating a Sequential Access File 5 Reading Data from a Sequential Access File 6 Updating Sequential Access Files

More information

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

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 12 Streams and File I/O Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output,

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 The C++ standard libraries provide an extensive set of input/output capabilities. C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function

More information

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

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York CSc 10200 Introduc/on to Compu/ng Lecture 19 Edgardo Molina Fall 2011 City College of New York 18 Standard Device Files Logical file object: Stream that connects a file of logically related data to a program

More information

Fundamentals of Programming Session 27

Fundamentals of Programming Session 27 Fundamentals of Programming Session 27 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we

More information

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

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes: C++ Binary File I/O C++ file input and output are typically achieved by using an object of one of the following classes: ifstream for reading input only. ofstream for writing output only. fstream for reading

More information

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

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010 TEST 1 CS 1410 Intro. To Computer Science Name KEY October 13, 2010 Fall 2010 Part I: Circle one answer only. (2 points each) 1. The decimal representation of binary number 11011 2 is a) 19 10 b) 29 10

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

A SHORT COURSE ON C++

A SHORT COURSE ON C++ Introduction to A SHORT COURSE ON School of Mathematics Semester 1 2008 Introduction to OUTLINE 1 INTRODUCTION TO 2 FLOW CONTROL AND FUNCTIONS If Else Looping Functions Cmath Library Prototyping Introduction

More information

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

VuZs Team's Work. CS201 Spring Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May :52 CS201 Spring2009 5 Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May 2010 17:52 MIDTERM EXAMINATION Spring 2009 CS201- Introduction to Programming Shared & Solved by vuzs Team

More information

Chapter 11 Customizing I/O

Chapter 11 Customizing I/O Chapter 11 Customizing I/O Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/fall_2010/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using C++

More information

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7. Data File Handling Introduction Data File Handling The fstream.h Header file Data Files Opening and Closing File Steps to process a File in your Program Changing the behavior of Stream Sequential I/O With Files Detecting

More information

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

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary Reading from and Writing to Files Section 3.12 & 13.1 & 13.5 11/3/08 CS150 Introduction to Computer Science 1 1 Files (3.12) Data stored in variables is temporary We will learn how to write programs that

More information

I/O streams

I/O streams I/O streams 1-24-2013 I/O streams file I/O end-of-file eof reading in strings Browse the following libraries at cplusplus.com String Library STL: Standard Template Library (vector) IOStream Library HW#2

More information

PROGRAMMING EXAMPLE: Checking Account Balance

PROGRAMMING EXAMPLE: Checking Account Balance Programming Example: Checking Account Balance 1 PROGRAMMING EXAMPLE: Checking Account Balance A local bank in your town is looking for someone to write a program that calculates a customer s checking account

More information

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

Class Example. student.h file: Declaration of the student template. #ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED Class Example student.h file: Declaration of the student template. #ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED #include #include using namespace std; class student public:

More information

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

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing Input Data 1 Streams 2 Streams Conceptual Model of a Stream Associating a File Stream with a File Basic Stream Input Basic Stream Output Reading Single Characters: get() Skipping and Discarding Characters:

More information

Study Material for Class XII. Data File Handling

Study Material for Class XII. Data File Handling Study Material for Class XII Page 1 of 5 Data File Handling Components of C++ to be used with handling: Header s: fstream.h Classes: ifstream, ofstream, fstream File modes: in, out, in out Uses of cascaded

More information

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

We will exclusively use streams for input and output of data. Intro Programming in C++ C++ Input/Output: Streams The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: 1 istream

More information

File handling Basics. Lecture 7

File handling Basics. Lecture 7 File handling Basics Lecture 7 What is a File? A file is a collection of information, usually stored on a computer s disk. Information can be saved to files and then later reused. 2 File Names All files

More information

Lecture 5 Files and Streams

Lecture 5 Files and Streams Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,

More information

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

for (int i = 1; i <= 3; i++) { do { cout << Enter a positive integer: ; cin >> n; // Workshop 1 #include using namespace std; int main () int n, k; int sumdigits; for (int i = 1; i n; cin.clear (); cin.ignore (100,

More information

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

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers. cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

More information

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

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 Topic: File input/output I. Streams II. Access methods III. C++ style Input, output, random access Stream classes: ifstream, ofstream IV. C style The FILE data type Opening files Writing to, reading text

More information

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

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*... Input/output Remember std::ostream? namespace std { class ostream { /*... */ }; } extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; 7 / 24 std::istream std::ostream std

More information

Software Design & Programming I

Software Design & Programming I Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 3 Introduction

More information

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

AC55/AT55 OBJECT ORIENTED PROGRAMMING WITH C++ DEC 2013 Q.2 a. Discuss the fundamental features of the object oriented programming. The fundamentals features of the OOPs are the following: (i) Encapsulation: It is a mechanism that associates the code and data

More information

C++ How to Program 14.6

C++ How to Program 14.6 C++ How to Program 14.6 14.6 Random-Access Files pg.611-pg.612 -Unlike sequential files, R.A. files are instant-access applications. Any transaction-processing system. Requiring rapid access to specific

More information

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

Preview 8/28/2018. Review for COSC 120 (File Processing: Reading Data From a File) Preview Relational operator If, if--if, nested if statement Logical operators Validating Inputs Compare two c-string Switch Statement Increment decrement operator While, Do-While, For Loop Break, Continue

More information

C++ STREAMS; INHERITANCE AS

C++ STREAMS; INHERITANCE AS C++ STREAMS; INHERITANCE AS PUBLIC, PROTECTED, AND PRIVATE; AGGREGATION/COMPOSITION Pages 731 to 742 Anna Rakitianskaia, University of Pretoria C++ STREAM CLASSES A stream is an abstraction that represents

More information

Streams. Rupesh Nasre.

Streams. Rupesh Nasre. Streams Rupesh Nasre. OOAIA January 2018 I/O Input stream istream cin Defaults to keyboard / stdin Output stream ostream cout std::string name; std::cout > name; std::cout

More information

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

Advanced File Operations. Review of Files. Declaration Opening Using Closing. CS SJAllan Chapter 12 2 Chapter 12 Advanced File Operations Review of Files Declaration Opening Using Closing CS 1410 - SJAllan Chapter 12 2 1 Testing for Open Errors To see if the file is opened correctly, test as follows: in.open("cust.dat");

More information

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

This can be thrown by dynamic_cast. This is useful device to handle unexpected exceptions in a C++ program Abstract class Exception handling - Standard libraries - Generic Programming - templates class template - function template STL containers iterators function adaptors allocators -Parameterizing the class

More information

DISK FILE PROGRAM. ios. ofstream

DISK FILE PROGRAM. ios. ofstream [1] DEFINITION OF FILE A file is a bunch of bytes stored on some storage media like magnetic disk, optical disk or solid state media like pen-drive. In C++ a file, at its lowest level is interpreted simply

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

Module C++ I/O System Basics

Module C++ I/O System Basics 1 Module - 36 C++ I/O System Basics Table of Contents 1. Introduction 2. Stream classes of C++ 3. Predefined Standard Input/Output Streams 4. Functions of class 5. Functions of class

More information

Chapter 11 Customizing I/O

Chapter 11 Customizing I/O Chapter 11 Customizing I/O Bjarne Stroustrup www.stroustrup.com/programming Overview Input and output Numeric output Integer Floating point File modes Binary I/O Positioning String streams Line-oriented

More information

Introduction. Lecture 5 Files and Streams FILE * FILE *

Introduction. Lecture 5 Files and Streams FILE * FILE * Introduction Lecture Files and Streams C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file, and

More information

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

DATA FILE HANDLING FILES. characters (ASCII Code) sequence of bytes, i.e. 0 s & 1 s DATA FILE HANDLING The Language like C/C++ treat everything as a file, these languages treat keyboard, mouse, printer, Hard disk, Floppy disk and all other hardware as a file. In C++, a file, at its lowest

More information