Lecture 5 Files and Streams
|
|
- Erick Peters
- 6 years ago
- Views:
Transcription
1 Lecture 5 Files and Streams
2 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, and read this information back later All file access is controlled by a file pointer :- a pointer to a structure which is created when you open a file contains information about the file you opened Once the file is opened, refer to file via this pointer, NOT by its name. The file pointer is a variable of type FILE
3 FILE *
4 FILE *
5 FILE * As you can see FILE * is a complex structure which holds information about the file system. This information differs from different operating systems, and file system types. To make the C language portable an abstraction is used The C library contains a number of file access functions which use the FILE * abstraction to process the information
6 C++ File operations C++ provides a number of classes to perform output and input of characters to / from files These are specified to allow read, write, and read / write Unlike C these classes have different names as follows ofstream : A stream class to write to files ifstream : A stream class to read from files fstream : A stream class to both read and write from/to files.
7 Get File Name File processing : order of Open File with open operations File Open? No Report Error yes Read or write DATA no FINISHED? yes Close File close end
8 Opening a file To open a file we need to create a file object of the correct type. Once this is done we use the open method to see if the file can be accessed. In the following example we open a file for writing 1 #include <fstream> std::ofstream FileOut; 5 6 FileOut.open("File.txt",std::ios::out); 7 // check to see if we can open the file 8 if (!FileOut.is_open()) 9 { 10 std::cerr <<"Could not open File for writing "<<std::endl; 11 exit(exit_failure); 12 }
9 Stream IO When a file is opened a file descriptor is returned and this file descriptor is used for each subsequent I/O operation, when any operation is carried out on the file descriptor its is known as a stream. When a stream is opened the stream object created is used for all subsequent file operations not the file name.
10 std::fstream open method 1 void open ( const char * filename, ios_base::openmode mode = ios_base::out ); The open method takes two parameters. By default we only need to specify one which is the name of the file to access. However we can pass an additional mode parameter which allows us to specify different operations such as read/write. Also we can specify if the data is to be written as text (default) or binary
11 flag value std::ios_base::app std::ios_base::ate IO Modes opening mode (append) Set the stream's position indicator to the end of the stream before each output operation. (at end) Set the stream's position indicator to the end of the stream on opening. std::ios_base:: binary (binary) Consider stream as binary rather than text. std::ios_base:: in std::ios_base:: out std::ios_base:: trunc (input) Allow input operations on the stream. (output) Allow output operations on the stream. (truncate) Any current content is discarded, assuming a length of zero on opening.
12 checking file open Once the stream object s open method has been called we can check to see if it was successful 1 #include <fstream> std::ofstream FileOut; 5 6 FileOut.open("File.txt",std::ios::out); 7 // check to see if we can open the file 8 if (!FileOut.is_open()) 9 { 10 std::cerr <<"Could not open File for writing "<<std::endl; 11 exit(exit_failure); 12 }
13 closing a file close when a program finishes with a file it should close it using close method 1 FileOut.close(); close performs housekeeping tasks such as flushing (emptying) buffers and breaking connections with the stream object.
14 Reading and writing a Stream Once a stream has been opened there are three types of unformatted I/O which may be performed these are as follow 1. Character at a time I/O. 2. Line at a time I/O 3. Direct I/O
15 Access to the file Once the stream object is associated to a file we use the insertion and extraction operators to read and write data << is the insertion operator and can be used to write data to the stream object >> is the extraction operator and can be used to read data from the stream object These operators are overloaded to work with all standard data types There are also a number of methods for character / line at a time I/O
16 1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 #include <cstdlib> 5 6 int main(int argc, char *argv[]) 7 { 8 if (argc <=1) 9 { 10 std::cerr <<"Usage FileWrite [filename] "<<std::endl; 11 exit(exit_failure); 12 } std::ofstream FileOut; FileOut.open(argv[1],std::ios::out); 17 // check to see if we can open the file 18 if (!FileOut.is_open()) 19 { 20 std::cerr <<"Could not open File : "<<argv[1]<<" for writing "<<std::endl; 21 exit(exit_failure); 22 } int a=10; 25 char b='c'; 26 float c=22.3; 27 double d= ; 28 std::string s("hello file transfer"); FileOut<<a<<std::endl; 31 FileOut<<b<<std::endl; 32 FileOut<<c<<std::endl; 33 FileOut<<d<<std::endl; 34 FileOut<<s<<std::endl; FileOut.close(); 37 return EXIT_SUCCESS; 38 } Insertion example c hello file transfer
17 1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 #include <cstdlib> 5 6 int main(int argc, char *argv[]) 7 { 8 if (argc <=1) 9 { 10 std::cerr <<"Usage FileWrite [filename] "<<std::endl; 11 exit(exit_failure); 12 } std::ifstream FileIn; FileIn.open(argv[1]); 17 // check to see if we can open the file 18 if (!FileIn.is_open()) 19 { 20 std::cerr <<"Could not open File : "<<argv[1]<<" for reading "<<std::endl; 21 exit(exit_failure); 22 } int a; 25 char b; 26 float c; 27 double d; 28 std::string s; FileIn>>a; 31 FileIn>>b; 32 FileIn>>c; 33 FileIn>>d; 34 FileIn>>s; FileIn.close(); 37 std::cout << a<<"\n"<<b<<"\n"<<c<<"\n"<<d<<"\n"<<s<<std::endl; return EXIT_SUCCESS; 40 } c hello extraction example Note that the >> method for the string only reads to the 1st space
18 Input Functions To input a character we use the get method This inputs a character at a time from the specified stream This is shown in the following example.
19 1 #include <iostream> 2 #include <fstream> 3 #include <cstdlib> 4 5 int main(int argc, char *argv[]) 6 { 7 if (argc <=1) 8 { 9 std::cerr <<"Usage FileWrite [filename] "<<std::endl; 10 exit(exit_failure); 11 } std::ifstream FileIn; FileIn.open(argv[1]); 16 // check to see if we can open the file 17 if (!FileIn.is_open()) 18 { 19 std::cerr <<"Could not open File : "<<argv[1]<<" for writing "<<std::endl; 20 exit(exit_failure); 21 } 22 char data; 23 while (!FileIn.eof() ) 24 { 25 FileIn.get(data); 26 std::cout <<data; 27 } 28 std::cout<<std::endl; 29 FileIn.close(); 30 return EXIT_SUCCESS; 31 } Open file for reading and check if ok loop until we reach the end of the file (eof) Use the get method to read a character into the variable data
20 Output Functions To output characters we can use the put method This outputs a character at a time to the specified stream This is shown in the following example.
21 1 #include <iostream> 2 #include <fstream> 3 #include <cstdlib> 4 5 int main(int argc, char *argv[]) 6 { 7 if (argc <=2) 8 { 9 std::cerr <<"Usage FileWrite [infile] [outfile] "<<std::endl; 10 exit(exit_failure); 11 } std::ofstream FileOut; 14 std::ifstream FileIn; FileIn.open(argv[1]); 17 FileOut.open(argv[2]); // check to see if we can open the file 20 if (!FileOut.is_open() &&!FileIn.is_open()) 21 { 22 std::cerr <<"Could not open one of the files : "<<std::endl; 23 exit(exit_failure); 24 } while(!filein.eof()) 27 FileOut.put(FileIn.get()); FileOut.close(); 30 FileIn.close(); return EXIT_SUCCESS; 33 } Open two file streams and check if ok While not eof on the input file get a char from the ip file and write it to the op file
22 Line at a time I/O The previous functions have all used character at a time processing. When dealing with text files we can use line at a time I/ O The line is usually terminated with the newline character \n If we are writing a line we place the NULL (\0) char to specify the end.
23 Line Input Line at a time input is provided by the following function 1 istream& getline ( istream&, string& str, char delim ); 2 istream& getline ( istream&, string& str ); This function is passed an open stream to read from A string object to read the data too Additionally we can specify a delimiter to specify when to terminate the current read operation By default this is the \n character but we can change this to any character we like.
24 1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 #include <cstdlib> int main(int argc, char *argv[]) 8 { 9 if (argc <=1) 10 { 11 std::cout <<"Usage FileRead [filename] "<<std::endl; 12 exit(exit_failure); 13 } std::fstream FileIn; 16 FileIn.open(argv[1],std::ios::in); 17 if (!FileIn.is_open()) 18 { 19 std::cout <<"File : "<<argv[1]<<" Not found Exiting "<<std:: endl; 20 exit(exit_failure); 21 } std::string LineBuffer; 24 unsigned long int LineNumber=1; 25 while(!filein.eof()) 26 { 27 getline(filein,linebuffer,'\n'); 28 std::cout <<LineNumber<<" : "<<LineBuffer<<std::endl; 29 ++LineNumber; 30 } 31 FileIn.close(); 32 return EXIT_SUCCESS; 33 } open file for reading Declare a string to store data use getline to read up to the \n character
25 Reading from the console 1 #include <iostream> 2 #include <string> 3 #include <cstdlib> 4 5 int main(void) 6 { 7 std::cout << "Please enter a line:\n"; 8 std::string s; 9 getline(cin,s); 10 std::cout << "You entered " << s << '\n'; 11 return EXIT_SUCCESS; 12 } by using cin we can read from the console
26 Binary I/O The previous functions operated with either one character at a time or a line at a time Sometimes desirable to read or write complete structures to or from a file. This is done using the following binary I/O functions 1 std::istream& read(char *buffer, std::streamsize num); 2 std::ostream& write(const char *buffer, std::streamsize num);
27 Binary I/O Example write 1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 #include <cstdlib> class Point 8 { 9 public : 10 float x; 11 float y; 12 float z; 13 }; int main(int argc, char *argv[]) 16 { if (argc <=1) 19 { 20 std::cout <<"Usage BinaryWrite [filename] "<<std::endl; 21 exit(exit_failure); 22 } std::ofstream FileOut; 25 FileOut.open(argv[1],std::ios::out std::ios::binary); 26 if (!FileOut.is_open()) 27 { 28 std::cout <<"File : "<<argv[1]<<" Not found Exiting "<<std:: endl; 29 exit(exit_failure); 30 } Point p[100]; for(int i=0; i<100; ++i) 35 { 36 p[i].x=i; p[i].y=i; p[i].z=i; 37 } FileOut.write(reinterpret_cast <char *>(p),sizeof(point)*100); FileOut.close(); 42 return EXIT_SUCCESS; 43 } A class to hold data open a file for binary output Fill data with values (100) write out data
28 reinterpret_cast<>() As the read and write functions expect a pointer to character data we need to coerce the Point class to think it s a char * To do this we use 1 reinterpret_cast <char *>(p) This works in this case as the public elements of the class are the only elements seen to the coercion In some cases this is not same and it is best to write a file in and out method for the class
29 Binary I/O Example read 1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 #include <cstdlib> 5 6 using namespace std; 7 8 class Point{ 9 public : 10 float x; 11 float y; 12 float z; 13 }; int main(int argc, char *argv[]) 16 { if (argc <=1) 19 { 20 std::cout <<"Usage BinaryRead [filename] "<<std::endl; 21 exit(exit_failure); 22 } std::ifstream FileIn; 25 FileIn.open(argv[1],std::ios::in std::ios::binary); 26 if (!FileIn.is_open()) 27 { 28 std::cout <<"File : "<<argv[1]<<" Not found Exiting "<<std:: endl; 29 exit(exit_failure); 30 } 31 Point p[100]; 32 FileIn.read(reinterpret_cast <char *>(p),sizeof(point)*100); for(int i=0; i<100; ++i) 35 std::cout <<"["<<p[i].x<<","<<p[i].y<<","<<p[i].z<<"]\n"; FileIn.close(); 39 return EXIT_SUCCESS; 40 } A class to hold data open a file for binary input Read in data print it out
30 Positioning a stream There are several functions which allow the programmer to move the current position of the file stream. These are as follows 1. seekg and seekp. allow us to move to a position in the stream 2. tellg and tellp allow us to determine the current position in the stream.
31 Positioning a stream These functions allow us to change the position of the get and put stream pointers. Both functions are overloaded with two different prototypes. The first prototype is: 1 seekg ( position ); 2 seekp ( position ); Using this prototype the stream pointer is changed to the absolute position position (counting from the beginning of the file). The type for this parameter is the same as the one returned by functions tellg and tellp: the member type pos_type, which is an integer value. The other prototype for these functions is: 1 seekg ( offset, direction ); 2 seekp ( offset, direction );
32 positioning a stream The position element from the previous function can be one of the following std::ios::beg offset counted from the beginning of the stream std::ios::cur offset counted from the current position of the stream pointer std::ios::end offset counted from the end of the stream
33 File Parsing It is common to want to read information from a config file and setup a programs state dependent upon the information in the file One of the easiest methods is to read the text file a line at a time and split the line into tokens which can be acted upon We will re-visit this idea later in the year once we ve learnt some more C++
34 References Advanced Programming in the Unix Environment, W. Richard Stevens. Addison Wesley
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 informationThis 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 informationIS 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 informationLecture 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 informationConvenient 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 informationChapte 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 informationCSc 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 informationStreams 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 informationC++ 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 informationText 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 informationFundamentals 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 informationStrings 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 informationC++ 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 informationUnit-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 informationRandom File Access. 1. Random File Access
Random File Access 1. Random File Access In sequential file access, the file is read or written sequentially from the beginning. In random file access, you can skip around to various points in the file
More informationWriting a Good Program. 7. Stream I/O
Writing a Good Program 1 Input and Output I/O implementation is hardware dependent C++ does not, as a part of the language, define how data are sent out and read into the program The input and output (I/O)
More informationStreams. Ali Malik
Streams Ali Malik malikali@stanford.edu Game Plan Recap Purpose of Streams Output Streams Input Streams Stringstream (maybe) Announcements Recap Recap - Hello, world! #include int main() { std::cout
More informationStreams. 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 informationStreams - Object input and output in C++
Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input
More informationLecture 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 informationFundamentals of Programming Session 28
Fundamentals of Programming Session 28 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationCSE 333 Lecture 9 - intro to C++
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The
More informationCS 103 Unit 14 - Streams
CS 103 Unit 14 - Streams 1 2 I/O Streams '>>' operator used to read data from an input stream Always skips leading whitespace ('\n', ' ', '\t') and stops at first trailing whitespace '
More informationWeek 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 informationTypes of files Command line arguments File input and output functions Binary files Random access
Types of files Command line arguments File input and output functions Binary files Random access Program data is not persistent across uses of an application To preserve data for use at another time it
More informationCSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O
CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O PA2: encoding/decoding ENCODING: 1.Scan text file to compute frequencies 2.Build Huffman Tree 3.Find code for every symbol (letter) 4.Create new
More informationDeveloped 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 informationPiyush 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 informationCOMP322 - 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 informationC++ 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 informationCS 103 Unit 14 - Streams
CS 103 Unit 14 - Streams 1 2 I/O Streams '>>' operator reads from a stream (and convert to the desired type) Always skips leading whitespace ('\n', ' ', '\t') and stops at first trailing whitespace '
More informationInput/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 informationDirect Memory Access. Lecture 2 Pointer Revision Command Line Arguments. What happens when we use pointers. Same again with pictures
Lecture 2 Pointer Revision Command Line Arguments Direct Memory Access C/C++ allows the programmer to obtain the value of the memory address where a variable lives. To do this we need to use a special
More informationCSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O
CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O PA3: encoding/decoding ENCODING: 1.Scan text file to compute frequencies 2.Build Huffman Tree 3.Find code for every symbol (letter) 4.Create new
More informationChapter 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 informationPIC10B/1 Winter 2014 Exam I Study Guide
PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand
More informationC++ 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 informationFile 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 informationReading from files File errors Writing to files
Reading from files File errors Writing to files Program data is not persistent across uses of an application To preserve data for use at another time it must be saved in a file To retrieve data from a
More informationStrings and Stream I/O
Strings and Stream I/O C Strings In addition to the string class, C++ also supports old-style C strings In C, strings are stored as null-terminated character arrays str1 char * str1 = "What is your name?
More informationObject 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 informationAfter 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 informationLab 1: Introduction to C++
CPSC 221, Jan-Apr 2017 Lab 1 1/5 Lab 1: Introduction to C++ This is an introduction to C++ through some simple activities. You should also read the C++ Primer in your textbook, and practice as much as
More informationUEE1303(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 informationChapter 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 informationVuZs 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 informationCS2141 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 informationBITG 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 informationAnd Even More and More C++ Fundamentals of Computer Science
And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Friendship Inheritance Multiple Inheritance Polymorphism Virtual Members Abstract Base Classes File Input/Output Friendship
More informationOverview of Lecture. 1 Overloading I/O Operators. 2 Overloading << and >> for Fractions. 3 Formatted vs Unformatted Input
Overview of Lecture 1 Overloading I/O Operators 2 Overloading > for Fractions 3 Formatted vs Unformatted Input 4 Setting the State of a Stream 5 Questions PIC 10B Streams, Part II April 20, 2016
More informationAdvanced 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 informationSimple File I/O.
Simple File I/O from Chapter 6 http://www.cplusplus.com/reference/fstream/ifstream/ l / /f /if / http://www.cplusplus.com/reference/fstream/ofstream/ I/O Streams I/O refers to a program s input and output
More informationModule 11 The C++ I/O System
Table of Contents Module 11 The C++ I/O System CRITICAL SKILL 11.1: Understand I/O streams... 2 CRITICAL SKILL 11.2: Know the I/O class hierarchy... 3 CRITICAL SKILL 11.3: Overload the > operators...
More informationFall 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 informationChapter 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 informationStudy 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 informationChapter-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 informationIntermediate Programming / C and C++ CSCI 6610
Intermediate Programming / C... 1/16 Intermediate Programming / C and C++ CSCI 6610 Streams and Files February 22, 2016 Intermediate Programming / C... 2/16 Lecture 4: Using Streams and Files in C and
More informationObject 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 information10/23/02 21:20:33 IO_Examples
1 Oct 22 22:07 2000 extractor1.c Page 1 istream &operator>>( istream &in, Point &p ){ char junk; in >> junk >> p.x >> junk >> p.y >> junk; return in; 2 Oct 22 22:07 2000 extractor2.c Page 1 istream &operator>>(
More informationFundamentals 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 informationAn Implementation Demo. Project 08: Binary Tree I/O
An Implementation Demo Project 08: Binary Tree I/O Step By Step 1. Byte Counts 2. Huffman Tree and output nlr+lnr / nlrb 3. Construct from nlr+lnr / nlrb 4. Check the constructors with comparison 5. Input
More informationCSE 100: C++ IO CONTD., AVL TREES
CSE 1: C++ IO CONTD., AVL TREES Defining a "comparison class" 2 The prototype for priority_queue: The documentation says of the third template argument Compare: Comparison class: A class such that the
More informationChapter 12. Streams and File I/O
Chapter 12 Streams and File I/O Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag settings Introduction Streams Special objects Deliver
More informationFile 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 informationby Pearson Education, Inc. All Rights Reserved. 2
In Fig. 17.4, the file is to be opened for output, so an ofstream object is created. Two arguments are passed to the object s constructor the filename and the file-open mode (line 12). For an ofstream
More informationCSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory
More informationC++ 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 informationProgramming 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 informationInput 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 informationStreams. 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 informationCSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]
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
More informationFile 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 informationChapter 2. Procedural Programming
Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic
More informationPHY4321 Summary Notes
PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t
More informationCSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors
Announcements CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors HW 1 is available on-line through the website (on the Calendar ). Be sure to read through this information as you start
More informationStream States. Formatted I/O
C++ Input and Output * the standard C++ library has a collection of classes that can be used for input and output * most of these classes are based on a stream abstraction, the input or output device is
More informationA 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 informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ 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 informationMultiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationCSE 100: HUFFMAN CODES AND C++ IO
CSE 100: HUFFMAN CODES AND C++ IO Huffman s algorithm: Building the Huffman Tree 2 0. Determine the count of each symbol in the input message. 1. Create a forest of single-node trees containing symbols
More informationby Pearson Education, Inc. All Rights Reserved. 2
Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed
More informationCSE 100: HUFFMAN CODES
CSE 100: HUFFMAN CODES Code A Symbol Codeword S 00 P 01 A 10 M 11 Corresponding Binary Tree Code B Symbol Codeword S 0 P 1 A 10 M 11 Code C Symbol Codeword S 0 P 10 A 110 M 111 Problem Definition (revisited)
More informationLecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)
Lecture 10 Class string Namespaces Preprocessor directives Macros Conditional compilation Command line arguments Character handling library void* TNCG18(C++): Lec 10 1 Class string Template class
More informationChapter 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 informationProgrammazione. Prof. Marco Bertini
Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Hello world : a review Some differences between C and C++ Let s review some differences between C and C++ looking
More informationQUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING
QUESTION BANK DEPARTMENT:EEE SEMESTER: V SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING UNIT III PART - A (2 Marks) 1. What are the advantages of using exception handling? (AUC MAY 2013) In C++,
More informationDISK 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 informationFundamental 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 informationCPE 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 informationConsider 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 informationChapter 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 informationStudy recommendations for Quiz 5 - Chapter 5
Study recommendations for Quiz 5 - Chapter 5 Review Chapter 5 content in: your textbook, the Example Pages, and in the Glossary on the website Review the revised Order of Precedence able (including arithmetic,
More informationC++ 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 informationC Legacy Code Topics. Objectives. In this appendix you ll:
cppfp2_appf_legacycode.fm Page 1 Monday, March 25, 2013 3:44 PM F C Legacy Code Topics Objectives In this appendix you ll: Redirect keyboard input to come from a file and redirect screen output to a file.
More informationToday 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 informationPROGRAMMING IN C++ CVIČENÍ
PROGRAMMING IN C++ CVIČENÍ INFORMACE Michal Brabec http://www.ksi.mff.cuni.cz/ http://www.ksi.mff.cuni.cz/~brabec/ brabec@ksi.mff.cuni.cz gmichal.brabec@gmail.com REQUIREMENTS FOR COURSE CREDIT Basic requirements
More informationCS242 COMPUTER PROGRAMMING
CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing
More informationBasic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable
Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is
More informationios 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