0% found this document useful (0 votes)
3 views

Module_4_IO Streams and Files_Lecture Notes (1)

This document covers C++ I/O streams and file handling, explaining the concepts of input and output streams, stream classes, and the hierarchy of classes used for console and file operations. It details how to define, open, read from, and write to text and binary files using various C++ classes and functions. Additionally, it includes example programs demonstrating the use of file operations and the handling of data structures.

Uploaded by

Chandan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module_4_IO Streams and Files_Lecture Notes (1)

This document covers C++ I/O streams and file handling, explaining the concepts of input and output streams, stream classes, and the hierarchy of classes used for console and file operations. It details how to define, open, read from, and write to text and binary files using various C++ classes and functions. Additionally, it includes example programs demonstrating the use of file operations and the handling of data structures.

Uploaded by

Chandan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

MODULE 4: I/O Streams and Files

C++ STREAMS
A stream 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 data to the program is called
the input stream and the destination stream that receives output from the program is called the output stream. A
program extracts the bytes from an input stream and inserts bytes into an output stream.

C++ STREAM CLASSES


The C++ I/O streams contains hierarchy of classes that are used to define various streams to deal with both the
console and disk files. These classes are called as stream classes. The figure below shows the hierarchy of the
stream classes used for both input and output operations with the console unit. These classes are declared in the
header file iostream. This file should be included in all the programs that communicate with the console unit.

ios is the base class for istream (input stream) and ostream (output stream) which are base classes for iostream
(input/output stream). The class ios is declared as the virtual base class so that only one copy of its members
are inherited by the iostream.The class ios provides support for formatted and unformatted I/O operations.
Class istream is overloaded with >> operator. Class ifstream is derived from istream, this class
provides input operations. It is used to read from files. It contains open ( ) function with default input mode.
Inherits the function get ( ), getline ( ), read ( ), seekg ( ) and tellg ( ) functions from istream.
Class ostream is overloaded with << operator. Class ofstream is derived from ostream, this class
provides output operations. It is used to write to files. It contains open ( ) function with default output mode.
Inherits the function put ( ), write ( ), seekp ( ), tellp ( ) functions from ostream.
Class fstream is stream class used to read from and write to files.
MODULE 4: I/O Streams and Files

Stream classes for console operations


TEXT FILES
Defining Files
Files can be defined in three possible types.
1. ifstream <filename> (input file stream)
2. ofstream <filename> (output file stream)
3. fstream <filenamr> (I/O file stream)
The ifstream file is a read-only file and one can only read from the file defined as ifstream. The ofstream file is
an output-only file, and one can only write to the defined as ofstream. The fstream is used for both input and
output.
Opening Files
Files can be opened using constructors and open functions.
Using constructors we can open a file with a statement such as
ofstream ofstream_object (“fewlines.dat”);
The file modes have not been specified. The file mode is assumed to be ios::out when the object of ofstream
class is defined. After defining fewlines.dat to be a physical name for entryfile logical name the data written to
the entryfile will be written to fewlines.dat. the logical name will vanish when the program is over, but
physical file name will be there until somebody renames or deletes the file.
ifstream ifstream_object (“fewlines.dat”);
The file modes have not been specified. The file mode is assumed to be ios::in when the object of ifstream
class is defined.
Physical filename “fewlines.dat” remains the same in both the statements.
Using open ( ) member function we can open a file with a statement such as
ofstream ofstream_object;
ofstream_object.open (“fewlines.dat”); // opening a file to write to the file

ifstream ifstream_object;
ifstream_object.open (“fewlines.dat”); // opening a file to read from the file
MODULE 4: I/O Streams and Files

Reading from and Writing to Files


To read and write from a file overloaded operators >> and << must be used.
Closing Files
The function close ( ) is used without any arguments to close a file. The allocated file handler is deallocated
and the buffers are flushed when a file is closed.
Program: To write to a file and read and display the same.
//WriteReadText.cpp
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#include<iostream>
#include<string.h>
#include<fstream>
using namespace std;
class Students
{
public:
string name;
float marks;
};

int main()
{
Students S;
int n;
cout<<"Enter no. of student: ";
cin>>n;
ofstream save("Data.txt");
if(!save)
{
cout<<"\nFile not found!!";
return 0;
}
for(int i=1;i<=n;i++)
{
cout<<"Details of the student:-"<<endl;
cout<<"Name: ";
cin>>S.name;
cout<<"Marks: ";
cin>>S.marks;
save<<"Details of the student:-"<<endl;
save<<"Name: "<<S.name<<endl;
save<<"Marks: "<<S.marks<<endl<<endl;
}
string str;
MODULE 4: I/O Streams and Files
ifstream in("Data.txt");
cout<<"\nData stored in the file:-"<<endl;
while(getline(in,str))
{
cout<<str<<endl;
}
return 0;
}

One needs to use either get() and put() (for reading char by char) or use getline() function for reading lines with
spaces.

Using get() and put( )


The Program below reads lines until $ and displays the lines as they are back on the screen. It uses two
functions for reading and writing characters, that is, get() and put(). Their syntax is as follows:
cin.get(ch) (reads a character from cin and stores what is read in ch)
cout.put(ch) (reads a character ch and writes to cout)
Program: use of get and put funstions
//GetPut.cpp
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#include <iomanip>
int main( )
{
char ch;
ofstream EntryFile("FewLines.dat");
If( EntryFile!=NULL)
{
Cout<<”Enter Text”;
Cin>>ch;
EntryFile.put(ch);
}
EntryFile.close( );
ifstream DisplayFile("FewLines.dat");
while(!DisplayFile.eof( ))
{
DisplayFile.get(ch);
cout << ch;
}
DisplayFile.close( );
return 0;
}
Input
MODULE 4: I/O Streams and Files
Acharya Institute of technology
Output
Acharya Institute of technology

Working of the program:


The put() function is called to write characters into this file. One can read a character and write that character in
the EntryFile. << is used to enter data in a file.
After this, the same file is opened in the read mode so that one can read from it.
While reading, get() skips the white spaces before any character. Thus, if get() is reading "...this is testing", it
will skip the first three spaces and then read and return 't' (the first character of the string). This is correct for
normal cases, but here the need is not to skip the whitespaces.

Using getline ( )
We can even use cout and cin with getline() instead of get(). The same getline() available with cin is also
available to all istream objects. It is also available to the DisplayFile().
Program: Usage of getline( )
//Getline.cpp
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
char InputLine[80], OutputLine[80];
ofstream EntryFile("FewLines.dat");
while(true)
{
cin.getline(InputLine, 80);
if(!strcmp(InputLine, "End")) break;
EntryFile << InputLine << endl;
}
EntryFile.close();
ifstream DisplayFile("FewLines.dat");
while(!DisplayFile.eof())
{
DisplayFile.getline(OutputLine, 80);
cout << OutputLine << endl;
}
DisplayFile.close();
return 0;
}
Input
Imagination is
more important
than knowledge
End
Output
Imagination is more important than knowledge
MODULE 4: I/O Streams and Files
Working of the program:
When the following statements are executed, the line (maximum 80 characters as specified in the argument or
until the carriage return is encountered) is read into the input (if cin is used to invoke getline()) or read from the
file (if file name is used to invoke getline()).
cin.getline(InputLine, 80);
DisplayFile.getline(OutputLine, 80);

BINARY FILES
These files are more useful for storing structures of information.
Opening a Binary File
We can open a binary file using constructor and open( ) member function.
A binary file can be opened using a constructor. The constructors for ofstream and ifstream are acceptable for
text files. For binary files, another constructor with two arguments is needed. The first argument is the name of
the file and the second one is the file mode.
// Using open methods
ofstream BE_StudFile_Out;
BE_StudFile_Out.open("BE.dat", ios::out | ios::binary | ios::trunc);
// Using constructor
ofstream BE_StudFile_Out("BE.dat", ios::in | ios::binary | ios::trunc);
The first example is using the open method and the second one is using a constructor. Programmers, therefore,
usually use the second method.
The same effect can be achieved by writing either of the following:
ofstream BE_StudFile_Out("BE.dat", ios::out | ios::binary | ios::trunc); //constructor
Mode ios::out means it is a file that is opened for the purpose of writing, ios::binary means there is no
translation that will take place while we write and with the output file there is another parameter ios::trunc
which means that if the file that we are trying to open and write the contents is already present the previous
contents are deleted so that we can write the new contents.
ifstream BE_StudFile_In;
BE_StudFile_In.open("BE.dat", ios::in | ios::binary); //open member function

Reading from and Writing to Binary Files


Two member functions for ifstream and ofstream objects are useful in reading and writing. Both of them have
similar syntax. They are
OfstreamFileObject.write((char *) &<the object>, sizeof(<the same object>))
for writing in the file and
IfStreamFileObject.read((char *) &<the object>, sizeof(<the same object>))
for reading from the file.
It is important to understand that the file read and write is performed objectwise and not elementwise.
One reads the complete object from the file or writes the complete object to the file using a single read or write.
The object here can even be a struct variable such as struct student of Program below.
Respective statements are needed to read from the keyboard and construct the object for providing
input to the file, that is, one has to first read the student object and then write to a file. Similarly, one needs to
write the object on the screen after reading it from the fi le. Here, both reading the object from the keyboard
and writing it to the screen are done elementwise. Only when one is reading from a fi le or writing to it, one
reads and writes objectwise.
MODULE 4: I/O Streams and Files

Closing Binary Files


A close( ) function is needed to close the binary file.
Example:
BE_StudFile_Out.close( );
The syntax for closing a file is
FileObject.close( );
It also deallocates the file handle and flushes the allocated buffers as in the case of text files.

Using Binary Files


Let us consider an example of a structure student. It contains the following entities: roll number, name,
address, and an array of five subjects the student has opted for. There are two simple programs; First program
allows the user to add the details of a few students to the student file and second program displays the data.
Both open methods and constructors have been used to open the files.

Program: Reading and Writing to a binary file


#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
using namespace std;
class timeVal{
int hh, mm, ss;
char ampm[3];
public:
void setdata(int h, int m, int s, const char* half)
{
hh = h;
mm = m;
ss = s;
strcpy(ampm, half);
}
void showdata()
{
cout << "\nThe Time is : ";
cout << setfill('0') << setw(2) << hh << ":";
cout << setfill('0') << setw(2) << mm << ":";
cout << setfill('0') << setw(2) << ss << " ";
cout << ampm << endl << endl;

}
};

int main()
{
timeVal writeObj, readObj;
MODULE 4: I/O Streams and Files
int hh, mm, ss;
char ampm[3];
cout << "Enter Hours : ";
cin >> hh;
cout << "Enter Minutes : ";
cin >> mm;
cout << "Enter Seconds : ";
cin >> ss;
cout << "Enter am or pm : ";
cin >> ampm;
writeObj.setdata(hh,mm,ss,ampm);
ofstream outFile("TimeFile", ios::out | ios::binary);
if(!outFile)
{
cout << "Cannot open file.\n";
return 1;
}
outFile.write((char *) &writeObj, sizeof(timeVal));
cout << "\nWritten the time object successfully to binary file" << endl;
outFile.close();

// now, read back;


ifstream inFile("TimeFile", ios::in | ios::binary);
if(!inFile)
{
cout << "Cannot open file.\n";
return 1;
}
inFile.read((char *) &readObj, sizeof(timeVal));
cout << "\nRead the time object successfully from binary file" << endl;

readObj.showdata();
inFile.close();
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy