Sunday 27 December 2020

Streams and Files Using C++ (Object Oriented Programming).

 


                    Streams and Files

Objectives:


 To familiarize students with iostream library, predefined streams, formatted I/O, Disk files, reading and writing objects  
   

Tools: 

Turbo C++ IDE 


files in c++

Procedure:

  Writing C++ language program to perform the following tasks
       Writing person data to a file.

Streams:

 C++ performs I/O through streams. A stream is a general name given to a flow of data and an abstraction that either produces or consumes information. We have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively. All stream behave in the same manner, even if the actual physical devices to which they are linked differ. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the console, a disk file, or a network connection. Streams are a clean ways to deal with input/output without having every part of your code understand the difference between a keyboard and a network. For example C++ implements streams within class hierarchies defined in iostream. IOstreams can be used for a wide variety of data manipulations such as:
       A 'stream' is internally nothing but a series of characters. The characters may be either normal characters (char) or wide characters (wchar_t). Streams provide you with a universal characterbased interface to any type of storage medium (for example, a file), without requiring you to know the details of how to write to the storage medium. Any object that can be written to one type of stream, can be written to all types of streams. In other words, as long as an object has a stream representation, any storage medium can accept objects with that stream representation.
       Streams work with built-in data types, and you can make user-defined types work with streams by overloading the insertion operator (<<) to put objects into streams, and the extraction operator (>>) to read objects from streams.
       The stream library's unified approach makes it very friendly to use. Using a consistent interface for outputting to the screen and sending files over a network makes life easier. 
Input and output are actually information as a stream of characters. This makes sense because whatever we enter through a keyboard can only be characters. Suppose the user enters the number 7479. How do you know the user entered a number? The problem is that you don't really know. All you have is a set of 4 characters: '7', '4', '7' and '9'. It is completely up to you, the programmer, whether you want the input to be a number, to be a string, or to be fodder, whether the characters can be valid for the desired type totally depends upon whether that type can interpret the characters in the input stream as a description for an object of that type.
You have to get the input characters into a recognizable data type for them to be of any use other than as a character array. IO streams not only define the relation between a stream of characters and the standard data types but also allows you to define a relationship between a stream of characters and your own classes. It also allows you nearly limitless freedom to manipulate those streams both using object oriented interfaces and working directly on character buffers when necessary. The different elements of iostream library can be as follow:

Classes:

ios_base
Base class for streams
ios
Base class for streams
istream
Input stream (class)
ostream
Output stream (class)
iostream
Input/output stream (class)
ifstream
Input file stream class (class)
ofstream
Output file stream
fsteram
Input/output file stream class
istringstream
Input string stream
ostringstream
Output string stream
stringstream
Input/output string stream
streambuf
Base buffer class for streams
filebuf
File stream buffer
stringbuf
String stream buffer

Objects:

cin
Standard input stream
cout
Standard output stream
cerr
Standard output stream for errors
clog
Standard output stream for logging

Manipulators: 

ws
Turn on whitespace skipping on input
dec
Convert to decimal
oct 
Convert to octal
hex
Convert to hexadecimal
endl
Insert newline and flush the output stream
ends
Insert null character to terminate an output
flush 
Flush the output stream
lock 
Lock file handle
unclock
Unlock file handle

File:

 a file represent a sequence of byte on the disk where a group of related data is stored. File is created for permanent storage of data. It is ready made structure. In C++, we use a structure pointer of the file type to declare a file. C++ programming language provides number of functions to perform basic file operations. Few of them are as under: 
Function
Description
ofstream
Output file stream and is used to create files and to write information to files
ifstream
Input file stream and is used to read information from files
fstream
File stream generally and has the capability of both ofstream and ifstream which can create files, write information to files, and read information from files.

To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.

Opening Files – A file must be opened before you can read from it or write to it. Either the ofstream orfstream object may be used to open a file for writing or ifstream object is used to open a file for reading purpose only. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.

Void open(const char *filename, ios::openmode mode);

Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.
Mode flag
Description
ios::app
Append mode. All output to that file to be appended to the end
ios::ate
Open a file for output and move the read/write control tot the end of the file.
ios::in
Open a file for reading
ios::out
Open a file for writing
ios::trunk
If the file already exists, its contents will be truncated before opening a file

You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case it already exists, following will be the syntax:
ofstream outfile;
outfile.open(“file.dat”, ios::out | ios::trunc);

Similarly, you can open a file for writing and reading purpose as follows:
fstream afile;
afile.open(“file.dat”, ios::out  | ios::in);

Writing to a file – While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object such as follows.
ofstream ofs (“ a.text ”, ios::app);

Reading from a file – You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.
Closing a file – When a C++ program terminates it automatically closes flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination. Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.

Step 1: Create New C++ Program File and save it as lab12.cpp
Step 2: Write the following code as shown in figures below

Figure 34(a): Writing data to a file

Streams and Files program

Figure 34(b): Writing data to a file

Step 3: Save file again, compile and run it for required output as shown in figure below
Streams and Files output

Figure 34(c): Writing data to a file
Try these Task(s): Write C++ language program to perform following tasks
       Write a program that uses a single file for both reading and writing the data

       A file contains a list of names and telephone numbers in the following form: Name  Telephone No.
Write a C++ program to read the file and output the list in the tabular format. The name should be left-justified and numbers right-justified. Use a class object to store each set of data.

       Write an interactive, menu-driven program that will access the file created in program above and implement the following tasks: 

a)       To determine the telephone numbers of the specified person.
b)      To determine the name if a telephone number is given.
c)       To update the telephone number whenever there is a change.

No comments:

Post a Comment