UNIT V FILE HANDLING

Size: px
Start display at page:

Download "UNIT V FILE HANDLING"

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. The keyword using can also be used as a directive to introduce an entire namespace: // using #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: Function at() tells us which character lies at a given position. (e.g) String Sample( Computer ); Sample.at(2) return the character m 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: Concatenation and comparison of two strings are possible by using the following ways: = operator is used to assign one string object to another. + operator is used to concatenate two strings into one. = = operator to compare two string objects. Compare() function to compare two string objects. This function is analogous to the strcmp function. It can also determine if either string is smaller than the other. There is also an overload version of swap which compares a part of a given string to a part of another string. (ii) Swapping two strings: The function swap() helps in swapping two different string object values. If St1 and St2 are string objects, St1.Swap(St2) copies the value of St1 to St2 and vice versa. 4. Finding characteristics of a string. empty() checks if the string object contains any data. This function returns 1 if the function is empty, else it returns 0. size() it returns the size of a string. max_size() it returns maximum permissible size of a string. resize() it resize the string by the number supplied as an argument.

25 STL Container Class Introduction: A Container class is defined as a class that gives you the power to store any type of data. There are two types of container classes available in STL in C++, namely Simple Container Classes and Associative Container Classes. An Associative Container class associates a key to each object to minimize the average access time. Simple Container Classes : vector<> lists<> stack<> queue<> deque<> Associative Container Classes: map<> set<> multimap<> multiset<> Constructor of Vector class: There are 3 overloaded constructors in the vector class excluding the default one. You can create a vector object with predefined size and values for them.. Suppose you want to create a vector<int> object whose initial capacity will be 10 and all the values will be set to 2. Then you can create such an object using one of the overloaded versions of the vector constructor vector<int> nums(10,2); If you just want to specify the capacity but don t want to assign values for them then you can use the other constructor which accepts an integer to set the capacity of the vector like

26 vector<int> nums(100); The last constructor allows you to initialize the vector with data from other vectors or arrays or other collections. Suppose you want to copy one vector to the other then this constructor proves to be very handy. Here is the code snippet. vector<int> nums; for(int i=1;i<5;i++) nums.push_back(i); vector<int> codes(nums); Here codes is a vector. We have copied the contents of nums in codes using the constructor. Methods of vector class: Destroy() Eq() Lt() Ucopy() Ufill() assign() at() begin() back() capacity() clear() empty() end() erase() front() get_allocator() max_size() insert() operator= operator[] pop_back() push_back() rbegin() rend() reserve() resize() size() swap() ~vector()

27 assign() and size() : This method is used to assign an initial size to the vector. This method has 2 overloaded versions. Here we have used the first overloaded method. This method takes an integer argument to initialize the size of the vector. #include <iostream> #include <vector> #include <conio.h> using namespace std; int main() vector<char> codes; codes.assign(10);//assigning the size to 10. cout<<codes.size();//prints the size of the vector getch(); return 0; The next overloaded match takes 2 pointer as arguments. Here is a sample code #include <iostream> #include <vector> #include <conio.h> using namespace std; int main() char a[3]='a','b','c'; vector<char> orders; orders.assign(a,a+3); cout<<orders.size(); getch();

28 return 0; Here the pointer used are nothing but the array name. This concept owes to C. Basically array name is a pointer to that array. at(): As vector behaves like an open array, people expect it to show other behaviors of the array. at() is a method that takes an integer as argument and return the value at that location. So in a way it simulates the age-old array indexing. Here is a code snippet. #include <iostream> #include <vector> #include <conio.h> using namespace std; int main() vector<int> codes; for(int i=0;i<10;i++) codes.push_back(i); cout<<codes.at(9)<<endl; getch(); return 0; The output of this code will be 9. begin(), end(): In STL within containers the elements are accessed using iterators. Iterators are something like pointers. begin() and end() returns the iterator to the beginning and to the end of the container. Here one thing should be noted end() points to a location which is one after the physical end of the container.

29 These two methods are the most used ones in STL, because to traverse a container, you need to create an iterator. And then to initialize it s value to the beginning of the container. Here is the code to traverse a vector<>. This code make use of begin() and end() methods. #include <iostream> #include <vector> using namespace std; int main() vector<int> numbers; for(int i=0;i<10;i++) numbers.push_back(i); //Assiging to the beginning vector<int>::iterator k = numbers.begin(); //please note that k is kept less than //numbers.end() because end() points to somewhere which is beyond physical end. for(;k<numbers.end();k++) cout<<*k<<endl; return 0; front(), back(): front() method returns the element at the front of the vector. back() method returns the element at the back of the vector. Here is the code to understand its operations better. #include <iostream> #include <vector> using namespace std; int main() vector<int> m; for(int i=0;i<10;i++) m.push_back(i);

30 cout<<m.front()<<endl; cout<<m.back()<<endl; return 0; The output of this program is 0 9 capacity(), size() : capacity() returns the number of elements the vector can hold initially assigned. For a vector although it is not very important method. On the other hand the method size() returns the number of elements currently in the vector. Here is the code that will help you understand the difference between capacity() and size(). #include <iostream> #include <vector> using namespace std; int main() vector<int> m(100); cout<<m.capacity()<<endl; for(int i=0;i<10;i++) m.push_back(i); cout<<m.size()<<endl; return 0; The output of the program is

31 Lists The list class supports a bidirectional, linear list. Unlike a vector, which supports random access, a list can be accessed sequentially only. Since lists are bidirectional, they may be accessed front to back or back to front. Member Description reference back( ); Returns a reference to the last element in const_reference back() const; the list. iterator begins; Returns an iterator to the first element in const_iterator begin( ) const; the list. void clear( ); Removes all elements from the list. bool empty() const; Returns true if the invoking list is empty and false otherwise. iterator ends; Returns an iterator to the end of the list. const_iterator end( ) const; iterator erase(iterator i); Removes the element pointed to by i. Returns an iterator to the element after the one removed. iterator erase(iterator start, iterator end); Removes the elements in the range start to end. reference front( ); Returns a reference to the first element in const_reference front( ) const; the list. Understanding end( ): end( ) does not return a pointer to the last element in a container. Instead, it returns a pointer one past the last element. Thus, the last element in a container is pointed to by end( ) - 1. This feature allows us to write very efficient algorithms that cycle through all of the elements of a container, including the last one, using an iterator. When the iterator has the same value as the one returned by end( ), we know that all elements have been accessed.

32 Maps: The map class supports an associative container in which unique keys are mapped with values. In essence, a key is simply a name that you give to a value. Once a value has been stored, you can retrieve it by using its key. Thus, in its most general sense, a map is a list of key/value pairs. The power of a map is that you can look up a value given its key. For example, you could define a map that uses a person s name as its key and stores that person s telephone number as its value. Associative containers are becoming more popular in programming. As mentioned, a map can hold only unique keys. Duplicate keys are not allowed. To create a map that allows nonunique keys, use multimap. The map container has the following template specification: template <class Key, class T, class Comp less<key>, class Allocator allocator<t>> class map Here, Key is the data type of the keys, T is the data type of the values being stored (mapped), and Comp is a function that compares two keys. This defaults to the standard less( ) utility function object. Allocator is the allocator (which defaults to allocator) The following comparison operators are defined for map. ==, <, <=,!=, >, >= Member Description iterator begins; Returns an iterator to the first element const_iterator begin() const; in the map. void clear( ); Removes all elements from the map. size_type count(const key_type &k) const; Returns the number of times k occurs in the map.

33 bool empty( ) const; Returns true if the invoking map is empty and false otherwise. iterator ends; Returns an iterator to the end of const_iterator end( ) const; the list. void erase(iterator i); Removes the element pointed to by i. void erase(iterator start, iterator end); Removes the elements in the range start to end. size_type erase(const key_type &k) Removes from the map elements that have keys with the value k. iterator find(const key_type &k); Returns an iterator to the specified iterator insert(iterator i, Inserts val at or after the element const value_type &val); specified by i. An iterator to the element is returned. template <class miter> Inserts a range of elements. void insert(inlter start, miter end) pair<iterator, bool> Inserts val into the invoking map. An insert(const value_type &val); iterator to the element is returned. The element is inserted only if it does not already exist. If the element was inserted, pair<iterator, true> is returned. Otherwise, pair<iterator, false> is returned. Algorithms: Algorithms act on containers. Although each container provides support for its own basic operations, the standard algorithms provide more extended or complex actions. They also allow you to work with two different types of containers at the same time. To have access to the STL algorithms, you must include <algorithm> in your program. Algorithm Purpose adjacent_find Searches for adjacent matching elements

34 first match. binary_search y copy_backward. count count_if within a sequence and returns an iterator to the. Performs a binary search on an ordered sequence. Copies a sequence. Same as copy() except that it moves the first elements from the end of the sequence first. Returns the number of elements in the sequence. Returns the number of elements in the sequence that satisfy some predicate. equal Determines if two ranges are the same. find_end Searches a range for a subsequence find_first_of Finds the first element within a sequence find_if Searches a range for an element. includes Determines if one sequence includes all of the elements in another sequence. inplace_merge Merges a range with another range. Removing and Replacing Elements: Sometimes it is useful to generate a new sequence that consists of only certain items from an original sequence. One algorithm that does this is remove_copy( ). Its general form is shown here: template <classinmiter, class Outlter, class T> Outlter remove_copy(inlter start, initer end, Outlter result, const 1 &val); The remove_copy() algorithm copies elements from the specified range, removing those that are equal to val. It puts the result into the sequence pointed to by result and

35 returns an iterator to the end of the result. The output container must be large enough to hold the result. To replace one element in a sequence with another when a copy is made, use replace_copyo. Its general form is shown here: template <class initer, class Outlter, class T> Outlter replace_copy(inlter start, initer end, Outlter result, const T &old, const T &new); The replace_copy( ) algorithm copies elements from the specified range, replacing elements equal to old with new. It puts the result into the sequence pointed to by result and returns an iterator to the end of the result. The output container must be large enough to hold the result. IMPORTANT QUESTIONS PART A (2-MARKS) 1. What is Generic programming? 2. What is Function Template? 3. What is Class Template? 4. What are Streams? 5. What are C++ streams? 6. Define Predefined console stream 7. Define Unformatted I/o operations 8. Define formatted console operations 9. What are Manipulators? 10. What are the types of Manipulators? 11. Define custom / user defined manipulators 12.What is a File? 13. Explain the various file stream classes needed for File Manipulators. 14. What are the steps involving Opening and Closing of Files. 15.Define the term Standard Template Library (STL).

36 PART B(16 MARKS) 1. What is generic programming? What are its advantages and state some of its Applications? 2. What is Function template? Write a suitable example program. 3. Explain overloaded function templates. With suitable example program. 4. What is a class template? Explain the syntax of a class template with suitable Program. 5. Draw console stream class hierarchy and explain its members. 7. Explain the various methods of performing formatted stream I/O operations. 7. What are manipulators? List the various predefined manipulators supported by c++ I/O streams. 8. Explain how standard manipulators are implemented. 9. What is a File? What are steps involved in manipulating a file in a C++ programs? 10. What are file modes? Describe various file mode options available 12. What are file pointers? Describe get-pointers and put-pointers? 13. Expalin in detail about STL.

UNIT V FILE HANDLING

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 information

UNIT-5. When a C++ program begins execution, four built-in streams are automatically opened. They are: Stream Meaning Default Device

UNIT-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 information

Module 11 The C++ I/O System

Module 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 information

Fig: iostream class hierarchy

Fig: 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 information

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

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

More information

Object Oriented Programming In C++

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

More information

C++ Programming Lecture 10 File Processing

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

More information

Unit-V File operations

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

More information

IS 0020 Program Design and Software Tools

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

More information

Streams - Object input and output in C++

Streams - 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 information

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

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

More information

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

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

More information

Lecture 9. Introduction

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

More information

Developed By : Ms. K. M. Sanghavi

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

More information

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

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

More information

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING

QUESTION 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 information

Chapter 8 File Processing

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

More information

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

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

More information

Chapter-12 DATA FILE HANDLING

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

More information

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

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

More information

Chapter 14 Sequential Access Files

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

More information

by Pearson Education, Inc. All Rights Reserved. 2

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

More information

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

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

More information

Random File Access. 1. Random File Access

Random 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 information

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

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

More information

Introduction to C++ (Extensions to C)

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

More information

COMP322 - Introduction to C++

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

More information

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>

basic_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 information

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

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

More information

by Pearson Education, Inc. All Rights Reserved. 2

by 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 information

Function Templates. Consider the following function:

Function Templates. Consider the following function: Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But

More information

C++ Input/Output: Streams

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

More information

C++ files and streams. Lec 28-31

C++ files and streams. Lec 28-31 C++ files and streams Lec 28-31 Introduction So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output

More information

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

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

More information

Fundamentals of Programming Session 27

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

More information

Writing a Good Program. 7. Stream I/O

Writing 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 information

Fall 2017 CISC/CMPE320 9/27/2017

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

More information

Stream States. Formatted I/O

Stream 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 information

Advanced I/O Concepts

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

More information

Standard Library Reference

Standard Library Reference Standard Library Reference This reference shows the most useful classes and functions in the standard library. Note that the syntax [start, end) refers to a half-open iterator range from start to end,

More information

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

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

More information

C++ Scope Resolution Operator ::

C++ 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 information

Chapter 12 - C++ Stream Input/Output

Chapter 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 information

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

I 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 information

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

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

More information

Chapter 12: Advanced File Operations

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

More information

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

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

More information

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

I/O Streams and Standard I/O Devices (cont d.) Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

More information

Chapter 15 - C++ As A "Better C"

Chapter 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 information

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

JAYARAM 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 information

Objects and streams and files CS427: Elements of Software Engineering

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

More information

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides. Lecture 21 Standard Template Library STL: At a C++ standards meeting in 1994, the committee voted to adopt a proposal by Alex Stepanov of Hewlett-Packard Laboratories to include, as part of the standard

More information

CS201 - Introduction to Programming Glossary By

CS201 - 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 information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram 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 information

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

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

More information

by Pearson Education, Inc. All Rights Reserved. 2

by 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 information

Programming with Haiku

Programming with Haiku Programming with Haiku Lesson 2 Written by DarkWyrm All material 2010 DarkWyrm In our first lesson, we learned about how to generalize type handling using templates and some of the incredibly flexible

More information

Short Notes of CS201

Short 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 information

Chapter 3 - Notes Input/Output

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

More information

After going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file

After going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file 16 Files 16.1 Introduction At times it is required to store data on hard disk or floppy disk in some application program. The data is stored in these devices using the concept of file. 16.2 Objectives

More information

Chapte t r r 9

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

More information

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

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

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

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

More information

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

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

More information

CS201 Solved MCQs.

CS201 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 information

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

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

More information

Interview Questions of C++

Interview 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 information

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

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

More information

CS11 Advanced C++ Lecture 2 Fall

CS11 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 information

G52CPP C++ Programming Lecture 18

G52CPP C++ Programming Lecture 18 G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know

More information

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

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

More information

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

G52CPP C++ Programming Lecture 18. Dr Jason Atkin G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that

More information

Object Oriented Programming

Object 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 information

UNIT- 3 Introduction to C++

UNIT- 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 information

CS3157: Advanced Programming. Outline

CS3157: 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 information

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

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

More information

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

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

More information

UNIT IV-2. The I/O library functions can be classified into two broad categories:

UNIT 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 information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ 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 information

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

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

STL. Prof Tejada Week 14

STL. Prof Tejada Week 14 STL Prof Tejada Week 14 Standard Template Library (STL) What is the STL? A generic collection of commonly used data structures and algorithms In 1994, STL was adopted as a standard part of C++ Why used

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Lecture 5 Files and Streams

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

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

ios ifstream fstream

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

More information

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

Physical 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 information

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

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

More information

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

CSC 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 information

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4 Steven J. Zeil July 19, 2013 Contents 1 Overview of Sets and Maps 4 1 2 The Set ADT 6 2.1 The template header................................. 14 2.2 Internal type names.................................

More information

COMP322 - Introduction to C++

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

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Standard Library. Lecture 27. Containers. STL Containers. Standard Library

Standard Library. Lecture 27. Containers. STL Containers. Standard Library Standard Library Lecture 27 Containers (templates) Streams (I/O facilities) Standard Library Portable, type-safe, efficient Try to use as much as possible Heavy use of templates Streams: #include

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

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

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

More information