Streams in C++ Stream concept. Reference information. Stream type declarations
|
|
- Hannah Paul
- 5 years ago
- Views:
Transcription
1 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 from the stream only in the order arriving or stored, and it is not possible to read something twice, or go back in the stream to read previous bytes. The order it fixed. The data can have two directions. It can come in to the program from the stream, or come out from the program to the stream. A stream acting as a source for data (coming in to the program) is called an in-stream. If it act as destination for data (going out from the program) it is an out-stream. Only special streams can also offer random access, where you can go back and read bytes again. Most streams are text-streams, where every byte is considered one single character, and data is stored in human readable form, as characters. Streams in C++ All streams in C++ have a specific data-type. The data-type determine what operations that can be done on the specific stream. In addition all streams in C++ have a common data-type. It provide operations that are common for all streams. By using the common data-type instead of a specific it is possible to easily interchange one stream for another. For example in arguments to a function, where sometimes we want to read data from a file, and sometimes we want the same data from the keyboard. When you create a stream you must create the specific stream type you want. To get access to that type you must include the corresponding header file. cin, cout and cerr are predefined C++ stream variables that you already used. Input and output to other stream variables are written just the same. Only the stream variable will be different, causing the data source or destination to be different (for cin the source of data is the keyboard, for an input file stream the source would be a file). Reference information Stream type declarations UNIX terminal commands to find reference information: man ios man istream man ostream man basic_string man stringstream man fstream man ctype man... (do you get the pattern?) man numeric_limits The man-pages are sometimes hard to read and understand for the beginner programmer. It is also very difficult to know what to look for. The man-pages will however be available on the exam - so it is may be worthwhile to learn how to use them. If you do not know what to look up, look up something similar, or a good guess, and use the see also section to get further ideas. You can also use google to get ideas. Online reference information (not available on exam): Common stream types: #include <iostream> // declarations for reference to any stream // in this case references to cin and cout istream& cin_alias = cin; // or other stream ostream& cout_alias = cout; Standard streams: #include <iostream> // the following variables are defined by // default, you do not need to define them cin // for normal input (keyboard) cout // for normal output (screen) cerr // for error messages (screen) String streams (must be connected to string variable): #include <sstream> // create a in-string-stream variable iss istringstream iss; // create a out-file-stream variable oss ostringstream oss; File streams (must be connected by opening some file): #include <fstream> // create a in-file-stream variable ifs ifstream ifs; // create a out-file-stream variable ofs ofstream ofs;
2 Stream operations (1 of 2) Stream operations (2 of 2) Functions available on all streams (member functions): bool bad(); // check different error flags bool eof(); bool fail(); // most useful, operator! bool good(); void clear(); // clear error flags (ONLY) Functions available on istreams (member functions): istream& operator>> // formatted input istream& get(char& c); // istream& getline(char* s, streamsize n, // char delim); // int sync(); istream& ignore(streamsize n, int delim); istream& read(char* s, streamsize n); streampos tellg(); istream& seekg(streampos pos); Complementary free function (part of string library) istream& getline(istream&, string&, char); Functions available on ostreams (member functions): ostream& operator>> // formatted output ostream& put(char c); ostream& flush(); streampos tellp(); ostream& seekp(streampos pos); ostream& write(const char* s, streamsize n); Manage connections on stringstreams (member functions): void str(const string& s); string str(); Manage connections on fstreams (member functions): void open(const char* filename, ios_base::openmode mode); void close(); Open modes: ios::app ios::ate ios::binary ios::ate ios::in ios::out ios::trunc The following operations from previous page is commonly used only on file streams: streampos tellg(); istream& seekg(streampos pos); streampos tellp(); ostream& seekp(streampos pos, ios_base::seekdir); Seek dirs: ios::beg ios::cur ios::end The following operations from previous page is commonly used only on binary file streams: istream& read(char* s, streamsize n); ostream& write(const char* s, streamsize n); Stream use, result and chaining In many of the following examples we will use cin. Remember that cin in the examples can be replaced with any stream type variable. Result of stream operations and chaining: // the result of stream operations // is the stream itself // this allows chaining the operations cin >> foo >> bar >> fum; (((cin >> foo) >> bar) >> fum); // >--istream-< // >------istream------< //> istream < A stream can occur where C++ expects a boolean value. The stream is converted to bool as if not fail was called. if ( cin ) // if (! cin.fail() ) // stream is in working order (good) if (! cin ) // if ( cin.fail() ) // stream will not work, an error is set // will silently fail to do ANY input // until the error is handled Streams as parameters and return values Streams can be sent as parameters to functions. It allows you to do a generic function to read or write your data, and decide which stream to use later, when you call the function. N.B! Streams must always be references! void print_table(ostream& os) for (int i = 0; i < 10; i = i + 1) os << setw(4) << i << endl; ostream& print_it(ostream& os) os << It ; return os; ofstream file( my_file.txt ); print_table(file); print_table(cerr); print_it(cout) << works. << endl;
3 Examples: To end-of-file Examples: Fail-safe reading string line; // read integers until failure // THIS IS CORRECT while (cin >> foo) cout << foo; // do something with foo Common pitfall: // read integers until eof // WRONG WRONG ERROR WRONG BAD AVOID // DO NOT DO LIKE THIS while (! cin.eof() ) cin >> foo; // read something to foo cout << foo; // do something with foo // read integers until eof // CORRECTED BUT AVKWARD VERSION while (! cin.eof() ) cin >> foo; // read something to foo if (! cin.eof() ) cout << foo; // do something with foo // read an integer between 1-10 fail-safe cin >> foo; // read something to foo // test if everything was OK immediately if (! cin.fail() ) if (foo >= 1 && foo <= 10) // success, data valid else // good read, but invalid data // if it was not OK, find the specific error // always test worst case first since the // worst errors may trigger a less bad error else if (cin.bad()) // failed, unrecoverable else if (cin.eof()) // end of file, end of stream // can be reset with clear if the // stream is standard input (cin) else // fail // interpretation to data-type failed // you must acknowledge the error cin.clear(); // remove the offending data from the // stream by a call to sync, ignore, get // getline, or >> to another data-type cin.ignore(1024, \n ); Removing offending data Examples: Line by line string line; string field; // simple solution that allows your program // to take look at the bad data cin >> word; // as above, but a full line getline(cin, line); getline(cin, line, \n ); // read one field (separated with : ) getline(cin, field, : ); // ignore at most 1000 characters or // at most one full line (until newline) // (whichever comes first) cin.ignore(1000, \n ); // read lines until failure while (getline(cin, line)) cout << line; // do something... // read?what? until failure while (getline(cin >> foo, line)) cout << line << : << foo; // read one full line // then read the data on the line while (getline(cin, line)) istringstream iss; // or: iss(line) int count = 0; // ignore one full line cin.ignore(numeric_limits<streamsize>::max(), \n ); // ignore as much as possible until ; cin.ignore(numeric_limits<streamsize>::max(), ; ); // just like ignore to end of line while (cin.get(c) && c!= \n ) ; // not guaranteed to work in all cases // (we have experienced different behaviour // on different systems, use ignore instead) cin.sync(); // tell iss to read from the line variable iss.str(line); while (iss >> foo) // pitfall: early eof() count = count + 1; // observe how to format long cout lines cout << line contained << count << integers. << endl;
4 Examples: Type conversion Examples: Read a file (1 of 3) double string_to_double(const string& s) istringstream text_representation(s); double floating_point; text_representation >> floating_point; return floating_point; string double_to_string(double d) ostringstream text_representation; text_representation << d; return text_representation.str(); // read file (hardcoded litteral filename) ifstream infile; // open file for reading... infile.open( my_data.txt ); if (! infile) // read data... while (infile >> foo) cout << foo << endl; // close filestream as soon as input and // output to it is done! Examples: Read a file (2 of 3) Examples: Read a file (3 of 3) // read file (program ask for filename) ifstream infile; string my_file; cout << enter file name: ; cin >> my_file; // open file for reading... // N.B! you must use c_str() to get the // correct data-type from the string infile.open(my_file.c_str()); if (! infile) // read data... while (infile >> foo) cout << foo << endl; // read file (filename from command line) int main(int argc, char* argv[]) string my_file; if (argc < 2) cerr << Usage: << argv[0] << FILENAME << endl; // open and clear file... // you can declare and open at once ifstream infile(argv[1], ios::trunc); if (! infile) // read data... while (infile >> foo) cout << foo << endl;
5 Examples: Write a file Writing is essentially identical to reading. You can modify this in the same way as the previous examples reading a file (exercise). ofstream outfile; // open file for reading... outfile.open( my_data.txt ); if (! outfile) // write data... while (cin >> foo) outfile << foo << endl; Binary streams Some streams can be configures to be binary, where data can be read or written without conversion to text. It is then written exactly as stored in the computer memory by the specific computer type you are working on. Different computers store binary data in different ways. For example our thin client servers running Solaris use SPARC processors that store binary integers in bigendian form, whereas a PC running Windows use the x86 architecture using little-endian form. You can compare to how dates are written in different parts of the world. Some countries write the smallest unit first, like DD-MM-YY, whereas other write the larger unit first, like YY-MM-DD. When you write data in one format you must also take care to read it in the same form. This poses a problem when you transfer binary files between different computer platforms, or over the network. outfile.close(); For example, if you save a binary file for lab 3 at home ( little-endian ), and then read it again on our thin clients it will not work, unless you take actions to convert the read bytes to big-endian form. Endianness or byte-order Example: Binary files (1 of 2) #include <cmath> little endian big endian Address Memory 0x03 bit bit 24 0x02 bit bit 16 0x01 bit bit 8 0x00 bit 7... bit 0 Address Memory 0x03 bit 7... bit 0 0x02 bit bit 8 0x01 bit bit 16 0x00 bit bit 24 double pi_out = M_PI; // double pi_in = 0.0; cout << "out: " << pi_out << endl; ofstream outfile("pi.bin", ios::binary); if (! outfile) cerr << Error opening file << endl; outfile.write( reinterpret_cast<char*>(&pi_out), sizeof(pi_out) ); outfile.close(); ifstream infile("pi.bin", ios::binary); if (! infile) cerr << Error opening file << endl; infile.read( reinterpret_cast<char*>(&pi_in), sizeof(pi_in) ); cout << "in: " << pi_in << endl;
6 Example: Binary files (2 of 2) Writing strings (data-type string) binary is not suitable, as the representation in memory of a string contain addresses that are specific to the particular program execution, and will be invalid the next time the program is run. Thus it is not possible to write a string binary, and expect the same string when you read it back. You will get an error that crash your program. The same apply to many types of data. The basic types long, int, double, float, char is safe to write binary. Use the normal formatted output operator to write a string. To write a fix-length string you can use setw as usual. const int SIZE = 9; string s = long example data ; os << setw(size) << s.substr(0, SIZE); // writes long exam to stream const int SIZE = 9; string s = mini ; os << setw(size) << s.substr(0, SIZE); // writes mini to stream
Generate error the C++ way
Reference informa9on Lecture 3 Stream I/O Consult reference for complete informa9on! UNIX man- pages (available on exam): man topic man istream man ostream ios, basic_string, stringstream, ctype, numeric_limits
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 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 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 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 informationAdvanced 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 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 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 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 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 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 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 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 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 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 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 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 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 informationLecture 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 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 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 informationStreams 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 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 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 informationIntroduction. 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 informationFile 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 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 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 informationInput 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 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 informationI/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 informationChapter 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 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 informationFormatting 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 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 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 informationCS11 Advanced C++ Lecture 2 Fall
CS11 Advanced C++ Lecture 2 Fall 2006-2007 Today s Topics C++ strings Access Searching Manipulation Converting back to C-style strings C++ streams Error handling Reading unformatted character data Simple
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 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 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 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 informationPhysics 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 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 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 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 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 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 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 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 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 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 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 informationPhysical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.
File Structures Physical Files and Logical Files Chap 2. Fundamental File Processing Operations Things you have to learn Physical files and logical files File processing operations: create, open, close,
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 informationC++ 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 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 informationObjects 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 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 informationFig: iostream class hierarchy
Unit 6: C++ IO Systems ================== Streams: Θ A stream is a logical device that either produces or consumes information. Θ A stream is linked to a physical device by the I/O system. Θ All streams
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 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 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 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 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 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 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 informationC++ 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 informationInput/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 informationCS103L SPRING 2018 UNIT 7: FILE I/O
CS103L SPRING 2018 UNIT 7: FILE I/O I/O STREAMS IN C++ I/O: short for input/ouput Older term from mainframe days for getting data into and out of your program C++ offers object oriented abstractions to
More informationClass 14. Input File Streams. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)
Class 14 Input File Streams A program that reads 10 integers from a file int main() { string filename; // the name of the file to be opened ifstream fin; // the input file stream int array[10]; // an array
More informationCPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)
Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow
More informationUNIT V FILE HANDLING
UNIT V CONTENTS: Streams and formatted I/O I/O manipulators File handling Random access Object serialization Namespaces Std namespace ANSI String Objects Standard template library FILE HANDLING Streams:
More informationfor (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 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 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 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 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 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 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 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 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 informationc++ 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 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 informationChapter 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 informationSHORT 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 informationAll About: File I/O in C++ By Ilia Yordanov, ; C++ Resources
All About: File I/O in C++ By Ilia Yordanov, loobian@cpp-home.com www.cpp-home.com ; C++ Resources This tutorial may not be republished without a written permission from the author! Introduction This tutorial
More informationSystem 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 informationG52CPP C++ Programming Lecture 17
G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions
More informationMore File IO. CIS 15 : Spring 2007
More File IO CIS 15 : Spring 2007 Functionalia Office Hours Today 2 to 3pm - 0317 N (Bridges Room) HW 2 due on Sunday March 11, 11:59pm Note: Midterm is on MONDAY, March 12th Review: Thursday Today: Survey
More informationName Section: M/W T/TH Number Definition Matching (8 Points)
Name Section: M/W T/TH Number Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Iteration Counter Event Counter Loop Abstract Step
More informationObject Oriented Programming CS250
Object Oriented Programming CS250 Abas Computer Science Dept, Faculty of Computers & Informatics, Zagazig University arabas@zu.edu.eg http://www.arsaliem.faculty.zu.edu.eg Object Oriented Programming Principles
More information3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity
Chapter 3: Expressions and Interactivity 3.1 The cin Object Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley
More informationThe 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 informationCS101 Linux Shell Handout
CS101 Linux Shell Handout Introduction This handout is meant to be used as a quick reference to get a beginner level hands on experience to using Linux based systems. We prepared this handout assuming
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 informationNote 11/13/2014. They are like those i s, j s, and temp s that appear and disappear when the function starts and finishes...
CISC 2000 Computer Science II Fall, 2014 Note 11/13/2014 1 Review of operator overloading (a) Lab class: take-away ############################ # Pass-by-value parameters # ############################
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 informationDefinition Matching (10 Points)
Name SOLUTION 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. There are no syntax errors
More informationWeek 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 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 information