Module V C Files and Streams Subject Object

Module V C++ Files and Streams Subject : Object Oriented Programming Using C++ Subject Code: 17 EC 562 Sanjay B. Nayak Associate Professor K. S. SCHOOL OF ENGINEERING AND MANAGEMENT, BANGALORE - 560109 DEPARTMENT OF ELETRONICS AND COMMUNICATION ENGINEERING

Learning Objectives C++ I/O streams. Reading and writing sequential and random access files. I/O formatting using I/O manipulators. 2

C++ Files and Streams A stream in simple words is flow of data. C++ views each files as a stream. The operations associated with files are read and write C++ provides various classes to support these operations. 3

To perform file processing in C++, the header files essential are <iostream> and <fstream> includes <ifstream> and <ofstream> ios is the base class for all these classes. These classes provide several member functions that perform input/output operations. 4

Abbreviated C++ class hierarchy for input output streams 5

iostream -- contains basic information required for all stream I/O operations fstream -- contains information for performing file I/O operations iomanip -- contains information useful for performing formatted I/O with parameterized stream manipulators 6

How to open a file in C++ ? ofstream out. File(“sample. dat”, ios: out) OR ofstream out. File; out. File. open(“sample. dat”, ios: out) 7

How to close a file in C++? The file is closed implicitly when a destructor for the corresponding object is called OR by using member function close: out. File. close(); 8

File Open Modes ios: : app - (append) write all output to the end of file ios: : ate - data can be written anywhere in the file ios: : binary - read/write data in binary format ios: : in - (input) open a file for input ios: : out - (output) open afile for output ios: trunc -(truncate) discard the files’ contents if it exists 9

File Open Modes cont… ios: : nocreate - if the file does NOT exists, the open operation fails ios: : noreplace - if the file exists, the open operation fails 10

Reading and printing a sequential file in. File >> var 1 >> var 2 >> var 3 out. File<<“Name: “<<var 1<<“Age : “<<var 2<<endl; 11

File position pointer <istream> and <ostream> classes provide member functions for repositioning the file pointer (the byte number of the next byte in the file to be read or to be written. ) These member functions are: seekg (seek get) for istream class seekp (seek put) for ostream class 12

Examples of moving a file pointer in. File. seekg(0) - repositions the file get pointer to the beginning of the file in. File. seekg(n, ios: beg) - repositions the file get pointer to the n-th byte of the file in. File. seekg(m, ios: end) -repositions the file get pointer to the m-th byte from the end of file in. File. seekg(0, ios: end) - repositions the file get pointer to the end of the file The same operations can be performed with <ostream> function member seekp. 13

Member functions tellg() and tellp() Member functions tellg and tellp are provided to return the current locations of the get and put pointers, respectively. long location = in. File. tellg(); To move the pointer relative to the current location use ios: : cur in. File. seekg(n, ios: : cur) - moves the file get pointer n bytes forward. 14

Updating a sequential file Data that is formatted and written to a sequential file cannot be modified easily without the risk of destroying other data in the file. If we want to modify a record of data, the new data may be longer than the old one and it could overwrite parts of the record following it. 15

Problems with sequential files Sequential files are inappropriate for socalled “instant access” applications in which a particular record of information must be located immediately. These applications include banking systems, point-of-sale systems, airline reservation systems, (or any data-base system. ) 16

Random access files Instant access is possible with random access files. Individual records of a random access file can be accessed directly (and quickly) without searching many other records. 17

Example of a Program that Creates a Random Access File // Fig. 14. 11: clntdata. h // Definition of struct client. Data used in // Figs. 14. 11, 14. 12, 14. 14 and 14. 15. #ifndef CLNTDATA_H #define CLNTDATA_H struct client. Data { int account. Number; char last. Name[ 15 ]; char first. Name[ 10 ]; float balance; }; #endif 18

Creating a random access file // Creating a randomly accessed file sequentially #include <iostream. h> #include <fstream. h> #include <stdlib. h> #include "clntdata. h" int main() { ofstream out. Credit( "credit 1. dat", ios: : out); if ( !out. Credit ) { cerr << "File could not be opened. " << endl; exit( 1 ); } 19

client. Data blank. Client = { 0, "", 0. 0 }; for ( int i = 0; i < 100; i++ ) out. Credit. write (reinterpret_cast<const char *>( &blank. Client ), sizeof( client. Data ) ); return 0; } 20

<ostream> member function write The <ostream> member function write outputs a fixed number of bytes beginning at a specific location in memory to the specific stream. When the stream is associated with a file, the data is written beginning at the location in the file specified by the “put” file pointer. 21

The write function expects a first argument of type const char *, hence we used the reinterpret_cast <const char *> to convert the address of the blank. Client to a const char*. The second argument of write is an integer of type size_t specifying the number of bytes to written. Thus the sizeof( client. Data ). 22

Writing data randomly to a random file #include <iostream. h> #include <fstream. h> #include <stdlib. h> #include "clntdata. h" int main() { ofstream out. Credit( "credit. dat", ios: : ate ); if ( !out. Credit ) { cerr << "File could not be opened. " << endl; exit( 1 ); } 23

cout << "Enter account number " << "(1 to 100, 0 to end input)n? "; client. Data client; cin >> client. account. Number; while ( client. account. Number > 0 && client. account. Number <= 100 ) { cout << "Enter lastname, firstname, balancen? "; cin >> client. last. Name >> client. first. Name >> client. balance; 24

out. Credit. seekp( ( client. account. Number - 1 ) * sizeof( client. Data ) ); out. Credit. write( reinterpret_cast<const char *>( &client ), sizeof( client. Data ) ); cout << "Enter account numbern? "; cin >> client. account. Number; } return 0; } 25

Reading data from a random file #include <iostream> #include <iomanip. h> #include <fstream> #include <stdlib. h> #include "clntdata. h" void output. Line( ostream&, const client. Data & ); int main() { ifstream in. Credit( "credit. dat", ios: : in ); if ( !in. Credit ) { cerr << "File could not be opened. " << endl; exit( 1 ); } 26

cout << setiosflags( ios: : left ) << setw( 10 ) << "Account" << setw( 16 ) << "Last Name" << setw( 11 ) << "First Name" << resetiosflags( ios: : left ) << setw( 10 ) << "Balance" << endl; client. Data client; in. Credit. read( reinterpret_cast<char *>( &client ), sizeof( client. Data ) ); 27

while ( in. Credit && !in. Credit. eof() ) { if ( client. account. Number != 0 ) output. Line( cout, client ); in. Credit. read( reinterpret_cast<char *>( &client ), sizeof( client. Data ) ); } return 0; } 28

void output. Line( ostream &output, const client. Data &c ) { output << setiosflags( ios: : left ) << setw( 10 ) << c. account. Number << setw( 16 ) << c. last. Name << setw( 11 ) << c. first. Name << setw( 10 ) << setprecision( 2 ) << resetiosflags( ios: : left ) << setiosflags( ios: : fixed | ios: : showpoint ) << c. balance << 'n'; } 29

The <istream> function read in. Credit. read (reinterpret_cast<char *>(&client), sizeof(client. Data)); The <istream> function inputs a specified (by sizeof(client. Data)) number of bytes from the current position of the specified stream into an object. 30

C++ Stream I/O -- Stream Manipulators C++ provides various stream manipulators that performatting tasks. Stream manipulators are defined in <iomanip> These manipulators provide capabilities for setting field widths, setting precision, 31

C++ Stream I/O -- Stream Manipulators contd…. . setting and unsetting format flags, flushing streams, inserting a "newline" and flushing output stream, skipping whitespace in input stream 32

I/O -- Stream Manipulators setprecision ( ) Select output precision, i. e. , number of significant digits to be printed. Example: cout << setprecision (2) ; // two significant digits 33

I/O -- Stream Manipulators setw ( ) Specify the field width (Can be used on input or output, but only applies to next insertion or extraction). Example: cout << setw (4) ; // field is four positions wide 34

Stream I/O Format State Flags ios: : showpoint when set, show trailing decimal point and zeros ios: : showpos when set, show the + sign before positive numbers ios: : basefield ios: : dec use base ten ios: : oct use base eight ios: : hex use base sixteen 35

Stream I/O Format State Flags ios: : floatfield ios: : fixed ios: : scientific ios: : adjustfield ios: : left ios: : right ios: : internal use fixed number of digits use "scientific" notation use left justification use right justification left justify the sign, but right justify the value 36

. setf ( ) Allows the setting of an I/O stream format flag. Examples: // To show the + sign in front of positive numbers cout. setf (ios: : showpos) ; // To output the number in hexadecimal cout. setf (ios: : hex, ios: : basefield) ; 37


Important websites: http: //www. cplus. com/reference/iolibrary/ https: //tutorialink. com/cpp-manipulators. cpp https: //nptel. ac. in/courses/106/105/106105151 39
- Slides: 39