UNIT V FILE HANDLING
|
|
- Patience Horton
- 6 years ago
- Views:
Transcription
1 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: A stream is an object where a program can either insert or extract characters to or from it. The standard input and output stream objects of C++ are declared in the header file iostream. A steam is a sequence of bytes. It acts either as a source from which the input data can be obtained or as a destination to which the output data can be sent. The source stream that provides the data to the program is called the input stream and the destination stream that receives output from the program is called the output stream. All streams behave in the same way even though the actual physical devices they are connected to may differ substantially. Because all streams behave the same, the same I/O functions can operate on virtually any type of physical device. For example, you can use the same function that writes to a file to write to the printer or to the screen. The advantage to this approach is that you need learn only one I/O system. C++ STEAMS i/p stream i/p device Exception from i/p stream Program i/p streams o/p device
2 The C++ Stream Classes: Standard C++ provides support for its I/O system in <iostream>. The C++ I/O system is built upon two related but different template class hierarchies. The first is derived from the low-level I/O class called basic_streambuf. This class supplies the basic, low-level input and output operations, and provides the underlying support for the entire C++ I/O system. The class hierarchy that you will most commonly be working with is derived from basic_ios. This is a high-level I/O class that provides formatting, error checking, and status information related to stream I/O. (A base class for basic_ios is called ios_base, which defines several nontemplate traits used by basic_ios.) basic_ios is used as a base for several derived classes, including basic_istream, basic_ostream, and basic_iostream. These classes are used to create streams capable of input, output, and input/output, respectively. C++ s Predefined Streams: When a C++ program begins execution, four built-in streams are automatically opened. They are: Stream Meaning Default Device cin Standard input Keyboard cout Standard output Screen cerr Standard error output Screen clog Buffered version of cerr Screen Streams cin, cout, and cerr correspond to C s stdin, stdout, and stderr. By default, the standard streams are used to communicate with the console. Formatted I/O: The C++ I/O system allows you to format I/O operations. For example, you can set a field width, specify a number base, or determine how many digits after the decimal point will be displayed. There are two related but conceptually different ways that you can format data. First, you can directly access members of the ios class.
3 Specifically, you can set various format status flags defined inside the ios class or call various ios member functions. Second, you can use special functions called manipulators that can be included as part of an I/O expression. Formatting Using the ios Members: When the left flag is set, output is left justified. When right is set, output is right justified. When the internal flag is set, a numeric value is padded to fill a field by inserting spaces between any sign or base character. If none of these flags are set, output is right justified by default. Eg: #include <iostrearn> using narnespace std; int main() cout.setf(ios: :showpoint) cout.setf(ios: :showpos) cout << 100,0; // displays return 0; It is important to understand that setf( ) is a member function of the ios class and affects streams created by that class. Therefore, any call to setf( ) is done relative to a specific. Instead of making multiple calls to setf( ), you can simply OR together the values of the flags you want set. For example, this single call accomplishes the same thing: / / You can OR together two or more flags cout.setf(ios: :showpoint, ios: :showpos) Because the format flags are defined within the ios class, you must access their values by using ios and the scope resolution operator. For example, showbase by itself will not be recognized. You must specify ios::showbase.
4 Clearing Format Flags: The complement of setf( ) is unsetf( ). This member function of ios is used to clear one or more format flags. The flags specified by flags are cleared. (All other flags are unaffected.) The previous flag settings are returned. Using width( ), precision( ), and fill( ): In addition to the formatting flags, there are three member functions defined by ios that set these format parameters: the field width, the precision, and the fill character. The functions that do these things are width( ), precision( ), and fill( ), respectively. By default, when a value is output, it occupies only as much space as the number of characters it takes to display it. However, you can specify a minimum field width by using the width() function. Its prototype is shown here: streamsize width(streamsize w); Here,w becomes the field width, and the previous field width is returned. In some implementations, the field width must be set before each output. If it isn t, the default field width is used. The streamsize type is defined as some form of integer by the compiler. After you set a minimum field width, when a value uses less than the specified width, the field will be padded with the current fill character (space, by default) to reach the field width. If the size of the value exceeds the minimum field width, the field will be overrun. No values are truncated. When outputting floating-point values, you can determine the number of digits to be displayed after the decimal point by using the precision() function. Its prototype is shown here: streamsize precision(streamsize p);
5 Examples: Cout.width(5); Cout<<543; Will produce the following width Cout.precision(3); Cout ; Will produce 3.111(truncated) Cout.fill( * ); Cout.width(5); Cout<<456; Will produce * * Cout.setf(ios::showpoint); Cout.setf(ios::showpos); Cout.precision(3); Cout.width(5); Cout<<1.2; I/O Manipulators: Using Manipulators to Format I/O: The second way you can alter the format parameters of a stream is through the use of special functions called manipulators that can be included in an I/O expression.
6 Manipulator Purpose Input/Output Endl Output a newline character Output ends Output a null. Output internal Turns on internal flag. Output left Turns on left flag. Output noshowpoint Turns off showpoint flag. Output noshowpos Turns off showpos flag. Output nouppercase Turns off uppercase flag. Output resetiosfiags Turn off the flags Input/Output right Turns on right flag. Output setfill(int ch) Set the fill character Output setiosflags Turn on the flags Input/output setprecision Set the number of digits Output setw(int w) Set the field width to w. Output showbase Turns on showbase flag Output showpoint Turns on showpoint flag. Output showpos Turns on showpos flag. Output Here is an example that uses some manipulators: #include <iostrearm #include <iomanip> using narnespace std; int main() cout << setfill(? ) << setw(10) ; cout << 100 << endl; This displays???????100 As the examples suggest, the main advantage of using manipulators instead of the ios member functions is that they commonly allow more compact code to be written. You can use the setiosflags() manipulator to directly set the various format flags related to a stream. For example, this program uses setiosflags() to set the showbase and showpos flags:
7 #include <iostrearn> #include <lomanip> int main() cout << setiosflags(ios showpos); cout << setiosflags(ios showbase); cout << 123 ; return 0; The manipulator setiosflags( ) performs the same function as the member function setf 0. Designing our own manipulators: The general form of creating a manipulator without argument is ostream & manipulator (ostream & output, arguments-if-any)...(code) return output; The following function defines a manipulator called unit that displays inches ostream & unit(ostream & output) output<< inches ; return output; The statement cout<<36<<unit; Will produce the following output: 36 inches
8 File Handling: C++ File I/OL: File Classes: To perform file I/O, you must include the header <fstream> in your program. It defines several classes, including ifstream, ofstream, and fstream. These classes are derived from istream, ostream, and iostream, respectively. Remember, istream, ostream, and iostream are derived from ios, so ifstream, ofstream, and fstream also have access to all operations defined by ios. Another class used by the file system is filebuf, which provides low-level facilities The File Pointer: to manage a file stream. The file pointer is the common thread that unites the C I/O system. A file pointer is a pointer to a structure of type FILE. It points to information that defines various things about the file, including its name, status, and the current position of the file. In essence, the file pointer identifies a specific file and is used by the associated stream to direct the operation of the I/O functions. In order to read or write files, your program needs to use file pointers. To obtain a file pointer variable, use a statement like this: FILE *fp Opening and Closing a File: In C++, you open a file by linking it to a stream. Before you can open a file, you must first obtain a stream. There are three types of streams: input, output, and input/output. To create an input stream, you must declare the stream to be of class if stream. To create an output stream, you must declare it as class ofstream. Streams that will be performing both input and output operations must be declared as class fstream. For example, this fragment creates one input stream, one output stream, and one stream capable of both input and output:
9 if stream in; // input of stream out; // output fstrearn io; // input and output Once you have created a stream, one way to associate it with a file is by using openo. This function is a member of each of the three stream classes. The prototype for each is shown here: void ifstream::open(const char *fi1ename,ios::openmode mode= ios::in); void ofstream::open(const char *fi1ename, ios::openmode mode =ios::out ios::trunc); void fstream::open(const char *filename, ios::openmode mode = ios::in ios::out); Here, filename is the name of the file; it can include a path specifier. The value of mode determines how the file is opened. It must be one or more of the following values defined by open mode, which is an enumeration defined by ios (through its base class los_base). ios::app ios::ate ios::binary ios::in ios::out ios::trunk You can combine two or more of these values by ORing them together. Including ios::app causes all output to that file to be appended to the end. This value can be used only with files capable of output. Including ios::ate causes a seek to the end of the file to occur when the file is opened. Although ios::ate causes an initial seek to end-of-file, I/O operations can still occur anywhere within the file. The ios::in value specifies that the file is capable of input. The ios::out value specifies that the file is capable of output. The ios::binary value causes a file to be opened in binary mode.
10 By default, all files are opened in text mode. In text mode, various character translations may take place, such as carriage return/linefeed sequences being converted into new lines. However, when a file is opened in binary mode, no such character translations will occur. Understand that any file, whether it contains formatted text or raw data, can be opened in either binary or text mode. When creating an output stream using ofstream, any preexisting file by that name is automatically truncated. The following fragment opens a normal output file. ofstream out; out.open( test, ios::out); For ifstream, mode defaults to ios::in; for ofstream, and for fstream, it is ios::in I ios::out. Therefore, the preceding statement will usually look like this: Out.open( test ) ;// defaults to output and normal file If open() fails, the stream will evaluate to false when used in a Boolean expression. Therefore, before using a file, you should test to make sure that the open operation succeeded. Although it is entirely proper to open a file by using the open() function, most of the time you will not do so because the ifstream, ofstream, and fstream classes have constructor functions that automatically open the file. The constructor functions have the same parameters and defaults as the open() function. Therefore, you will most commonly see a file opened as shown here: ifstream mystrearn( myfile ) // open file for input As stated, if for some reason the file cannot be opened, the value of the associated stream variable will evaluate to false. Therefore, whether you use a constructor function to open the file or an explicit call to open( ), you will want to confirm that the file has actually been opened by testing the value of the stream.
11 You can also check to see if you have successfully opened a file by using the is_open( ) function, which is a member of fstream, ifstream, and ofstream. It has this prototype: bool is_opens; It returns true if the stream is linked to an open file and false otherwise. For example, the following checks if my stream is currently open: To close a file, use the member function closeo. For example, to close the file linked to a stream called mystream, use this statement: mystream close(); The close() function takes no parameters and returns no value. Writing a Character: The C I/O system defines two equivalent functions that output a character: putc() and fputco. (Actually, putc() is usually implemented as a macro.). The putc( ) function writes characters to a file that was previously opened for writing using the fopen() function. The prototype of this function is int putc(int ch, FILE *fr); where fr is the file pointer returned by fopen() and ch is the character to be output. The file pointer tells putc( ) which file to write to.if a putc( ) operation is successful, it returns the character written. Otherwise, it returns EOF. Reading a Character: There are also two equivalent functions that input a character: getc() and fgetc( ). Both are defined to preserve compatibility with older versions of C. The getc( ) function reads characters from a file opened in read mode by fopeno. The prototype of getc() is in getc(file *fr);
12 where fr is a file pointer returned by fopen( ). The getc( ) function returns an EOF when the end of the file has been reached. Therefore, to read to the end of a text file, you could use the following code: do ch = getc(fp); while(ch=eof); However, getc() also returns EOF if an error occurs. You can use ferror() to determine precisely what has occurred. Reading and Writing Text Files: It is very easy to read from or write to a text file. Simply use the << and >> operators the same way you do when performing console I/O, except that instead of using cin and cout, substitute a stream that is linked to a file. For example, this program creates a short inventory file that contains each item s name and its cost: #include <iostream> #include <fstrearm> using narnespace std; int main() ofstream out( inventory ) ; // output, normal file if(out) cout << Cannot open inventory file.\n ; return 1; out << Radios F << 39,95 << endl; out << toasters << << endl; out << Mixers << << endl; out.close() return 0; The following program reads the inventory file created by the previous program and displays its contents on the screen:
13 #include <iostream> #include <fstream> using narnespace std; int main() ifstream in( inventory ); // input if(in) cout << Cannot open inventory file.\n ; return 1; char item[20]; float cost; in>>item>>cost; cout<<item<<cost; in>>item>>cost; cout<<item<<cost; in>>item>>cost; cout<<item<<cost; in.close(); return 0; Random Access: In C++ s I/O system, you perform random access by using the seekg() and seekp() functions. Their most common forms are istream &seekg(off_type offset, seekdir origin); ostream &seekp(off_type offset, seekdir origin); Here, off_type is an integer type defined by ios that is capable of containing the largest valid value that offset can have. seekdir is an enumeration defined by ios that determines how the seek will take place. The C++ I/O system manages two pointers associated with a file.
14 One is the get pointer, which specifies where in the file the next input operation will occur. The other is the put pointer, which specifies where in the file the next output operation will occur. Each time an input or output operation takes place, the appropriate pointer is automatically sequentially advanced. However, using the seekg() and seekp() functions allows you to access the file in a nonsequential fashion. The seekg( ) function moves the associated file s current get pointer offset number of characters from the specified origin, which must be one of these three values: ios::beg Beginning-of-file ios::cur Current location ios::end End-of-file The seekp() function moves the associated file s current put pointer offset number of characters from the specified origin, which must be one of the values just shown.generally, random-access I/O should be performed only on those files opened for binary operations. The character translations that may occur on text files could cause a position request to be out of sync with the actual contents of the file. Obtaining the Current File Position: You can determine the current position of each file pointer by using these functions: pos_type tellg pos_type tellp Here, pos_type is a type defined by ios that is capable of holding the largest value that either function can return. You can use the values returned by tellg() and tellp( ) as arguments to the following forms of seekg() and seekp( ), respectively.
15 istream &seekg(pos_type pos); ostream &seekp(pos_type pos); These functions allow you to save the current file location, perform other file operations, and then reset the file location to its previously saved location. I/O Status: The C++ I/O system maintains status information about the outcome of each I/O operation. The current state of the I/O system is held in an object of type iostate, which is an enumeration defined by ios that includes the following members. Name Meaning ios::goodbit No error bits set ios::eofbit 1 when end-of-file is encountered; 0 otherwise ios::failbit 1 when a nonfatal I/O error has occurred; 0 otherwise ios::badbit 1 when a fatal I/O error has occurred; 0 otherwise Namespaces: The purpose of namespace is to localize the names of identifiers to avoid name collisions. The C++ programming environment has seen an explosion of variable, function, and class names. Prior to the invention of namespaces, all of these names competed for slots in the global namespace and many conflicts arose. For example, if your program defined a function called abs( ), it could (depending upon its parameter list) override the standard library function abs() because both names would be stored in the global namespace. Namespace Fundamentals: The namespace keyword allows you to partition the global namespace by creating a declarative region.
16 In essence, a namespace defines a scope. Anything defined within a namespace statement is within the scope of that namespace. Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name. A namespace declaration identifies and assigns a unique name to a user-declared namespaces. The format of namespaces is: namespace identifier entities Where identifier is any valid identifier and entities is the set of classes, objects and functions that are included within the namespace. For example: namespace mynamespace int a, b; In this case, the variables a and b are normal variables declared within a namespace called mynamespace. In order to access these variables from outside the mynamespace namespace we have to use the scope operator ::. For example, to access the previous variables from outside mynamespace we can write: mynamespace::a mynamespace::b The functionality of namespaces is especially useful in the case that there is a possibility that a global object or function uses the same identifier as another one, causing redefinition errors. For example:
17 // namespaces #include <iostream> using namespace std; namespace first int var = 5; namespace second double var = ; int main () cout << first::var << endl; cout << second::var << endl; return 0; Output: In this case, there are two global variables with the same name: var. One is defined within the namespace first and the other one in second. No redefinition errors happen thanks to namespaces. using: The keyword using is used to introduce a name from a namespace into the current declarative region. For example: // using #include <iostream>
18 using namespace std; namespace first int x = 5; int y = 10; namespace second double x = ; double y = ; int main () using first::x; using second::y; cout << x << endl; cout << y << endl; cout << first::y << endl; cout << second::x << endl; return 0; Output: Notice how in this code, x (without any name qualifier) refers to first::x whereas y refers to second::y, exactly as our using declarations have specified. We still have access to first::y and second::x using their fully qualified names. // using The keyword using can also be used as a directive to introduce an entire namespace: #include <iostream>
19 using namespace std; namespace first int x = 5; int y = 10; namespace second double x = ; double y = ; int main () using namespace first; cout << x << endl; cout << y << endl; cout << second::x << endl; cout << second::y << endl; return 0; Output: In this case, since we have declared that we were using namespace first, all direct uses of x and y without name qualifiers were referring to their declarations in namespace first. using and using namespace have validity only in the same block in which they are stated or in the entire code if they are used directly in the global scope. For example, if we had the intention to first use the objects of one namespace and then those of another one, we could do something like:
20 // using namespace example #include <iostream> using namespace std; namespace first int x = 5; namespace second double x = ; int main () using namespace first; cout << x << endl; using namespace second; cout << x << endl; return 0; Output: The STD Namespace: Standard C++ defines its entire library in its own namespace called std. using narnespace std This causes the std namespace to be brought into the current namespace, which gives you direct access to the names of the functions and classes defined within the library without having to qualify each one with std::.of course, you can explicitly qualify each name with std:: if you like.
21 For example, the following program does not bring the library into the global namespace. #include <iostream> int main() int val; std: :cout << Enter a number: ; std: :cin >> val; std: :cout << Ihis is your number: ; std::cout << std::hex << val; return 0; Here, cout, cin, and the manipulator hex are explicitly qualified by their namespace. That is, to write to standard output, you must specify std::cout; to read from standard input, you must use std::cin; and the hex manipulator must be referred to as std::hex. You may not want to bring the standard C++ library into the global namespace if your program will be making only limited use of it. However, if your program contains hundreds of references to library names, then including std in the current namespace is far easier than qualifying each name individually. ANSI String Objects: The strings are implemented in C as character arrays. However, character arrays have a few limitations when treated as strings. They cannot be compared like other variables. They cannot be assigned like normal variables. Initializing with another string is not directly possible. There are functions provided for strings in the library, prototypes of which are accessible using string.h file. These functions are not string function in true sense. They operate on character pointers. Therefore, it is desirable that to treat strings as separate objects and as character arrays. C++ overcomes these limitations by providing string objects.
22 C++ does not support a built-in string type. It does, however, provide for two ways of handling strings. Null-terminated character array sometimes referred to as a C string. The second way is as a class object of type string. Actually, the string class is a specialization of a more general template class called basic_string. In fact, there are two specializations of basic_string: string, which supports 8-bit character strings, and wstring, which supports widecharacter strings. Since 8-bit characters are by far the most commonly used in normal programming, string is the version of basic_string examined here. Given that C++ already contains some support for strings as nullterminated character arrays, it may at first seem that the inclusion of the string class is an exception to this rule. However, this is actually far from the truth. Here is why: Nullterminated strings cannot be manipulated by any of the standard C++ operators. Nor can they take part in normal C++ expressions. Operations on Strings: 1. Creation of strings: A String object can be created in the following three ways: a. Defining a string object in a normal way: We can write string StingName; to define the string object in a normal way. b. Defining a string object using initialization: We can write string AStringObject(AnotherString Object) or AStringObject = AnotherStirngObject to define and initialize AStringObject using AnotherStirngObject. c. Defining a string object using a constructor: We can write string AStringObject(value) or string AStringObject = Value
23 to use a single argument constructor to define AStringObject and initialize it with value. Example: // DefineStrings.cpp #include<iostream.h> #include<string.h> using namespace std; int main() string FirstString; // Normal definition string SecondString( Hi ); //Definition using one argument constructor string ThirdString(SecondString); //Definition using initialization FirstString = Hoe are you ; /* Using a conversion function from normal strng to the string object. This conversion function is an outcome of a non-explicit one argument constructor */ string ForthString = FirstString; //defining and initializing 2. Substring Operations: There are a few substring operations as well. a). Find location of a substring or a character in a given string: There is a function find() which finds the specific substring or character in a given substring. Find returns the location or position at which that character of that string resides in the given string. The first position is numbered as zero and second is numbered as 1 like C strings. b) Find the character at a Given Location in a given string: There is a function at() which tells us which character lies at a given position. If we define string FirstString( This is testing ); FirstString.at(1) returns h because h is a character at 1 st position.(remember the string starts from 0 th position). c) Insert a specific Substring at a Specific Place: We can insert a specific substring in a given place in the string using function insert(positionatwhichinsertiontobemade, StringToBeInserted).
24 The following example will show how a substring busy is inserted at position number 4 in the string How Are You to make it How busy Are You. d) Replacing Specific Character by Other Characters: We can replace specific sequence of characters (a substring) by another sequence of characters(i.e., another substring) in a given string. Our example shows how busy is replaced by lazy. Through our example, uses same number of characters in the replacement string, it is not necessary. We can even replace busy with busy and tired. e) Append Substring to a String. The append function is available to add a substring at the end of a given string. Append is called with just one argument; the substring to append. The following program has one such use of append. It appends friend to the SecondString variable to make it Hi friend!. 3. Operations involving Multiple Strings: (i) + = and compare function (ii) Swapping two strings. 4. Finding characteristics of a string.
UNIT 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 informationUNIT-5. When a C++ program begins execution, four built-in streams are automatically opened. They are: Stream Meaning Default Device
UNIT-5 C++ Streams - Like the C-based I/O system, the C++ I/O system operates through streams. A stream is a logical device that either produces or consumes information. A stream is linked to a physical
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 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 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++ 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationbasic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>
The C++ I/O System I/O Class Hierarchy (simplified) ios_base ios / \ istream ostream \ / iostream ifstream fstream ofstream The class ios_base -- public variables and methods The derived classes istream,
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 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 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 informationC++ Scope Resolution Operator ::
C++ Scope Resolution Operator :: C++The :: (scope resolution) operator is used to qualify hidden names so that you can still use them. You can use the unary scope operator if a namespace scope or global
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 informationIntroduction 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 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 informationby 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 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 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 12 - C++ Stream Input/Output
Chapter 12 - C++ Stream Input/Output 1 12.1 Introduction 12.2 Streams 12.2.1 Classic Streams vs. Standard Streams 12.2.2 iostream Library Header Files 12.2.3 Stream Input/Output Classes and Objects 12.3
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationCS201 Solved MCQs.
15.1 Answer each of the following: a. Input/output in C++ occurs as of bytes. b. The stream manipulators that format justification are, and. c. Member function can be used to set and reset format state.
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 informationWe 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 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 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 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 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 informationChapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams and Basic File I/O I/O Streams I/O
More informationI BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.
Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'
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 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 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 informationObject Oriented Programming
Object Oriented Programming Course Title: Object Oriented Programming Full Marks: 60 20 20 Course No: CSC161 Pass Marks: 24 8 8 Nature of Course: Theory Lab Credit Hrs: 3 Semester: II Course Description:
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 informationC++ Basics. Lecture 2 COP 3014 Spring January 8, 2018
C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing
More informationJayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT
CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions
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 informationJAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)
Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202
More informationWhat we will learn about this week:
What we will learn about this week: Streams Basic file I/O Tools for Stream I/O Manipulators Character I/O Get and Put EOF function Pre-defined character functions Objects 1 I/O Streams as an Introduction
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 informationChapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects
Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Copyright 2008 Pearson Addison-Wesley. All rights reserved.
More informationChapter 21 - C++ Stream Input/Output
Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
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 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 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 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 informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationLecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-
Lecture 3 Input and Output Review from last week Variable - place to store data in memory identified by a name should be meaningful Has a type- int double char bool Has a value may be garbage change value
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
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 informationcs3157: 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 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 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 informationChapter 21 - C++ Stream Input/Output
Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion
More informationPage 1
Virtual Functions (introduction) A virtual function is one that does not really exist but it appears real in some parts of the program. Virtual functions are advanced features of the object oriented programming
More informationGenerate 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 informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationUNIT IV-2. The I/O library functions can be classified into two broad categories:
UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known
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 information[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University
[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7 Seungkyu Lee Assistant Professor, Dept. of Computer Engineering Kyung Hee University Input entities Keyboard, files Output entities Monitor, files Standard
More informationFile Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9
File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9 Ziad Matni Dept. of Computer Science, UCSB Midterm Exam grades out! Announcements If you want to see your exams, visit
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 informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
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 informationUnit 1 : Principles of object oriented programming
Unit 1 : Principles of object oriented programming Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP) Divided Into Importance Procedure Oriented Programming In
More informationStandard I/O in C and C++
Introduction to Computer and Program Design Lesson 7 Standard I/O in C and C++ James C.C. Cheng Department of Computer Science National Chiao Tung University Standard I/O in C There three I/O memory buffers
More informationThe C++ Input/Output Class Hierarchy
C++ Programming: The C++ Input/Output Class Hierarchy 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Basics on C++ I/O The I/O class hierarchy The common base I/O
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 informationInterview Questions of C++
Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.
More informationLecture 14. Xiaoguang Wang. March 11th, 2014 STAT 598W. (STAT 598W) Lecture 14 1 / 36
Lecture 14 Xiaoguang Wang STAT 598W March 11th, 2014 (STAT 598W) Lecture 14 1 / 36 Outline 1 Some other terms: Namespace and Input/Output 2 Armadillo C++ 3 Application (STAT 598W) Lecture 14 2 / 36 Outline
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 information