Presentation is loading. Please wait.

Presentation is loading. Please wait.

Streams & Files in C++:Stream Classes, stream errors, disk file I/O with streams, File Pointers, Error handling in file I/O, File I/O with member functions,

Similar presentations


Presentation on theme: "Streams & Files in C++:Stream Classes, stream errors, disk file I/O with streams, File Pointers, Error handling in file I/O, File I/O with member functions,"— Presentation transcript:

1 Streams & Files in C++:Stream Classes, stream errors, disk file I/O with streams, File Pointers, Error handling in file I/O, File I/O with member functions, Overloading the extractions & Insertions operator, Memory as a Stream Object, Command Line Arguments, Multifile Programs.

2  Stream  A transfer of information in the form of a sequence of bytes  I/O Operations:  Input: A stream that flows from an input device ( i.e.: keyboard, disk drive, network connection) to main memory  Output: A stream that flows from main memory to an output device ( i.e.: screen, printer, disk drive, network connection)

3  Source stream that provides data to the program is called the input stream – ifstream class represents data flow from input disk files. Destination stream that receives output from the program is called the output stream - ofstream class represents data flow to disk files.

4 Input Device Output Device Program Input Stream Output Stream

5

6

7  Is the base class for the hierarchy.  It contains constants and member functions common to input and output operations of all kinds.  It defines properties of all stream classes.  It also contains pointer to streambuf class which contains the actual memory buffer into which data is read or written.  State bits and format flags are part of this class.

8  Are derived from ios.  Define objects that can be used for reading and writing.  istream class contains functions such as get(), getline() and read() and overloaded extraction (>>) operators.  ostream class contains functions such as put() and write() and overloaded insertion (<<) operators.

9  Is derived from istream and ostream by multiple inheritance.  Defines objects that can be used for reading as well as writing and can be used with devices such as disk files.

10  ifstream  Defines functionalities to perform read operation on files (input file stream)  ofstream  Defines functionalities to perform write operation on files (output file stream)  fstream  Defines functionalities to perform read as well as write operation on file.  filebuf  Used by other file stream classes to perform actual read/write of characters.

11  When a C++ program begins execution, four built-in stream objects are automatically opened: 1. cin- an object of istream_withassign, used for standard input using the keyboard. 2. cout- an object of ostream_withassign, used for standard buffered output on the screen. 3. cerr- an object of ostream_withassign, used for standard error output on the screen. 4. clog- an object of ostream_withassign, used for Buffered version of cerr on the screen.

12  iostream library:  : Contains cin, cout, cerr, and clog objects  : Contains parameterized stream manipulators  : Contains information important to user-controlled file processing operations

13 C++ supports a number of features that could be used for formatting the output. These features include:  ios class functions and flags.  Manipulators.  User-defined output functions.

14  The various functions for formatting are:  width() : specifies required field size for displaying output value.  precision() : specifies the number of digits to be displayed after decimal point.  fill() :specifies a character that is used to fill unused portion of a field.  setf() : sets format flag that controls the form of output display.  unsetf() : clears the flags specified.

15 Defining Field Width: width () used to define the width of the field to be used while displaying the output. Since it is a member function, it has to be invoked on an object. syntax : cout.width (w); Where w is the field width(number of columns).

16 54312 For example,the statements cout.width(7); cout<<543<<12<<”\n”; will produce the following output:

17 By default,the floating numbers are printed with six digits after the decimal point.However,we can specify the number of digits to be displayed after the decimal point while printing the floating-point numbers. This can be done by using the precision() member function as follows: cout.precision(d); Where d is the number of digits to the right of the decimal point. Default precision is 6 digits.

18 Example : cout.precision(2); cout<<1.347<<endl; cout<<1.54; o/p : 1.35 1.54

19 We can also combine the field specification with the precision setting. Example: cout.precision(2); cout.width(5); cout<<1.2345; The output will be: 1.23

20 We can use the fill() function to fill the unused positions by any desired character. It is used in the following form: cout.fill(ch); Where ch represents the character which is used for filling the unused positions.

21 Example: cout.fill(‘*’); cout.width(10); cout<<5250<<”\n”; The output would be: ******5250

22 The setf() function can be used as follows: cout.setf(arg1,arg2); The arg1 is one of the formatting flags defined in the class ios. The formatting flag specifies the format action required for the output. Another ios constant, arg2, known as bit field specifies the group to which the formatting flag belongs.

23

24  All the flags can be set using the setf() and unsetf() iosmember functions. Look at the following example:  cout.setf(ios::left); // left justify output text  cout >> “This text is left-justified”;  cout.unsetf(ios::left); // return to default (right justified)

25 Format requiredFlag(arg1)Bit-Field(arg2) Left-justified output Right-justified output Padding after sign or base Indicater(like +##20) ios::left ios::right ios::internal ios::adjustfield Scientific notation Fixed point notation ios::scientific ios::fixed ios::floatfield Decimal base Octal base Hexadecimal base ios::doc ios::oct ios::hex ios::basefield

26 Examples: cout.setf(ios::left,ios::adjustfied); cout.setf(ios::scientific,ios::floatfield);

27 Consider the following segment of code: cout.filll(‘*’); cout.setf(ios::left,ios::adjustfield); cout.width(15); cout<<”12345”<<”\n”; This will produce the following output: 12345**********

28 The statements cout.fill(‘*’); cout.precision(3); cout.setf(ios::internal,ios::adjustfield); cout.setf(ios::scientific,ios::floatfield); cout.width(15); cout<<-12.34567<<”\n”; will produce the following output: -*****1.235e+01

29 Manipulators are special functions that can be included in the I/O statements to alter the format parameters of a stream. To access manipulators, the file iomanip should be included in the program.

30

31  You insert these manipulators directly into the stream. For example, to output var in hexadecimal format, you can say  cout << hex << var; Note: The manipulators affect only the data that follows them in the stream, not the data that precedes them.

32

33 ManipulatorsEquivalent ios function setw()width() setprecision()precision() setfill()fill() setiosflags()setf() resetiosflags()unsetf()

34  Error-Status Bits  The stream error-status flags constitute an ios enum member that reports errors that occurred in an input or output operation.

35

36 ManipulatorMeaningEquivalent setw(int w) setprecision(int d) Set the field width to w Set the floating point precision to d. width() precision() setfill(int c)Set the fill character to cfill() setiosflags(long f)Set the format flag fsetf() resetiosflags(long f)Clear the flag specified by funsetf() EndifInsert new line and flush stream “\n”

37 Some examples of manipulators are given below: cout<<setw(10)<<12345; This statement prints the value 12345 right- justified in a field width of 10 characters.

38 The output can be made left-justified by modifying the statement as follows: cout<<setw(10)<<setiosflags(ios::left)<<12345;

39 One statement can be used to format output for two or more values. For example,the statement cout<<setw(5)<<setprecision(2)<<1.2345 <<setw(10)<<setprecision(4)<<sqrt(2) <<setw(15)<<setiosflags(ios::scientific) <<sqrt(3)<<endl; Will print all the three values in one line with the field size of 5,10,and 15 respectively.

40 Example: cout.precision(2);//previous state int p=cout.precision(4);//current state; When these statements are executed, p will hold the value of 2(previous state) and the new format state will be 4.We can restore the previous format state as follows: cout.precision(p)//p=2

41 We can design our own manipulators for certain special purpose.The general form for creating a manipulator without any arguments is: ostream & manipulator(ostream & output) { ………… …………(code) ………… return output } Here the manipulator is the name of the manipulator under creation.

42 The following function defines a manipulator called unit that dispalys”inches”: ostream & unit(ostream &output) { output<<”inches”; return output; } The statement cout<<36<<unit; will produce the following output 36 inches

43 We can also create manipulators that could represent a sequence of operations. Example: ostream & show(ostream & output) { output.setf(ios::showpoint); output.setf(ios::showpos); output<<setw(10); return output; }

44 In C++, the << output operator is referred to as the insertion operator because it inserts characters into a stream. Likewise, the >> input operator is called the extraction operator because it extracts characters from a stream. The functions that overload the insertion and extraction operators are generally called inserters and extractors, respectively.

45 All inserter functions have this general form: ostream &operator<<(ostream &stream, class_type &obj) { // body of inserter return stream; } Notice that the function returns a reference to a stream of type ostream., which is an output stream (ostream is a class derived from ios that supports output.)

46 Extractors are the complement of inserters. The general form of an extractor function is istream &operator>>(istream &stream, class_type &obj) { // body of extractor return stream; } Extractors return a reference to a stream of type istream, which is an input stream. The first parameter must also be a reference to a stream of type istream.

47

48  C++ provides the following classes to perform output and input of characters to/from files: ofstream: Stream class to write on files  ifstream: Stream class to read from files  fstream: Stream class to both read and write from/to files.

49 A file can be opened in two ways: 1. Using the constructor function of the class 2. Using the member function open () of the class

50  A constructor is used to initialize an object while it is being created. Here, the filename is used to initialize the file stream object. This involves the following steps: 1. Create a file stream object to manage the stream using the appropriate class i.e. ofstream to create the output stream, ifstream to create input stream, fstream can be used to create both the input and output stream. 2. Bind the file stream to the disk. This file stream is identified by a filename.  For example, the following statement opens a file named “results” for output  ofstream outfile(“results”);

51  In order to open a file with a stream object we use its member function open(): open (filename, mode);  Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

52  #include  int main ()  {  ofstream outfile;  char name[10];  outfile.open("sample.txt ");  cout<<"enter name";  cin>>name;  outfile <<name;  outfile.close();  return 0;  }  #include  int main ()  {  ifstream infile;  char name[10];  infile.open ("sample.txt");  infile >> name;  cout<<name;  infile.close();  return 0;  }

53

54 1. Opening a file in ios::out mode also opens it in the ios::trunc mode by default. 2. Both ios:app and ios::ate sets the file pointer to the end of the file, but they differ in the type of operations permitted on the file. ios:app allows to add data from end of file, whereas ios::ate allows to add or modify existing data anywhere in the file. In both the cases, the file is created if it does not exist. 3. ios::app can be used only with output files. 4. The stream classes ifstream and ofstream open files in read and write modes respectively by default. 5. For fstream class the mode parameter must be explicitly specified. 6. Modes can combine two or more parameters using the bitwise OR operator as below:  myfile.open ("example.txt", ios::out | ios::app);

55  A file must be closed to release all the resources allocated to it. It is known that the destructor normally does the cleanup operation. Whenever the file stream object goes out of scope or the program terminates its execution, the file is automatically closed by the destructor. The file can be explicitly closed using the close member function, to disconnect the file from the file stream. This member function takes no parameters, and what it does is to flush the associated buffers and close the file:  Stream_object.close();  Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.

56  eof() is a member function of ios class. It returns a non-zero value if end-of-file condition is encountered and zero otherwise. Hence the above statement terminates the program on reaching the end of file.  If (fin.eof() !=0) { exit 1; }

57  All I/O streams objects have, at least, one internal stream pointer.  ifstream object has a pointer known as the get pointer that points to the element to be read in the next input operation.  ofstream object has a pointer known as the put pointer that points to the location where the next element has to be written.  fstream objects have both, the get and the put pointers.

58  The file pointers are set to a suitable location initially based on the mode in which the file is opened.  Read-only mode: when the file is opened in read only mode, the input (get) pointer is initialized to point to the beginning of the file, so that the file can be read from the start.  Write-only mode: when the file is opened in write only mode, the existing contents of the file are deleted (if the given file already exists) and the output (put) pointer is set to point to the beginning of the file, so that the data can be written from the start.  Append mode: when the file is opened in append mode, the existing contents of the file remain unaffected (if the given file already exists) and the output (put) pointer is set to point to the end of the file, so that the data can be written (appended) at the end of the existing contents.

59 Member FunctionDescription tellg()Returns read position seekg(pos)Moves get pointer to the position specified seekg(offset, rpos)Moves the get pointer, by the offset specified, from the rpos(reference position) tellp()Returns write position seekp(pos)Moves the put pointer to the position specified seekp(offset, rpos)Moves the put pointer, by the offset specified, from the rpos(reference position)

60 ConstantDescription ios::beg offset counted from the beginning of the stream ios::curr offset counted from the current position of the stream pointer ios::endoffset counted from the end of the stream (offset must be a negative value)

61  int pos=filestream.tellg(); // Save current get positions  filestream.seekg(0,ios::beg); //seek to beginning of file  filestream.seekg(5,ios::cur); //seek 5 character forward  filestream.seekg(-15,ios::end); //seek 10 characters before the eof

62  #include  int main()  {  char str[80];  cout << "Enter a string" << endl;  cin>>str;  int len=strlen(str);  fstream file;  file.open(“TEXT”,ios::in|i os::out);  for(int i=0;i<len;i++)  file.put(str[i]);  file.seekg(0);  char ch;  while (file)  {  file.get(ch);  cout<<ch;  }  return 0;  }

63  C++ supports a feature that facilitates the supply of arguments to the main() function. These arguments are supplied at the time of invoking the program. They are typically used to pass the name of a data file to an application.  Example

64  Programs which involve the usage of multiple files are Multifile programs.  Reasons for Multifile programs.  There are several reasons for using Multifile programs  Class libraries  Organization of program,  Conceptual design of program

65  Software vendors furnish libraries of functions. Other programmers then combine these libraries with their own custom written routines to create an application for the end user. Libraries provide ready-made functions for a wide variety of fields.  A class library can take over a greater portion of the programming burden. An applications programmer, if the right class library is available, may find that only a minimal amount of programming is necessary to create a final product.

66  A class library usually includes two components: the interface and the implementation.  Interface: To use a class library, the programmer needs to access the various declarations, including class declarations. These declarations can be thought of as the public part of the library and are usually furnished in source-code form as a header file, with the.h extension. This is combined with the clients source code using an #include statement.

67  Implementation: The inner working of the member functions of the various classes need to be known by the programmer. The class developers don’t want to release the source code, since it might be illegally modified or pirated. Member functions – except for inline functions are therefore often distributed in object form, as.obj file or as library.lib file.

68  A project may involve several programmers working on it. Confining each programmer’s responsibility to a separate file helps organize the project and define more clearly the interface among different parts of the program.  It is also often the case that a program is divided into separate files according to the functionality. One file can handle the code involved in a graphics display, while the other handles mathematical analysis.


Download ppt "Streams & Files in C++:Stream Classes, stream errors, disk file I/O with streams, File Pointers, Error handling in file I/O, File I/O with member functions,"

Similar presentations


Ads by Google