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

Oop Notes Unit 4

This document discusses file input/output (I/O) streams in C++. It covers stream classes, reading and writing files, file pointers, error handling, and overloading extraction and insertion operators. The key concepts are using fstream to read and write files, functions like tellp(), seekg() and error checking functions like ferror() and perror().

Uploaded by

Shriram Kulkarni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Oop Notes Unit 4

This document discusses file input/output (I/O) streams in C++. It covers stream classes, reading and writing files, file pointers, error handling, and overloading extraction and insertion operators. The key concepts are using fstream to read and write files, functions like tellp(), seekg() and error checking functions like ferror() and perror().

Uploaded by

Shriram Kulkarni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Unit 4 Files and Streams

Data hierarchy, Stream and files, Stream Classes, Stream Errors, Disk File I/O with Streams, File
Pointers, and Error Handling in File I/O, File I/O with Member Functions, Overloading the Extraction and
Insertion Operators, memory as a Stream Object, Command-Line Arguments, Printer output

Page 1 of 12
4.1 Data hierarchy: Streams and Files
In C++ programming, we are using the iostream standard library, it provides cin and cout methods for
reading from input and writing to output respectively.

To read and write from a file we are using the standard C++ library called fstream. Let us see the data
types define in fstream library is:

Data Type Description


fstream It is used to create files, write information to files, and read information from files.
ifstream It is used to read information from files.
ofstream It is used to create files and write information to the files.

4.2 Stream Classes


In C++ stream refers to the stream of characters that are transferred between the program thread and
i/o. Stream classes in C++ are used to input and output operations on files and io devices. These classes
have specific features and to handle input and output of the program. The iostream.h library holds all the
stream classes in the C++ programming language. Let's see the hierarchy and learn about them,

ios class − This class is the base class for all stream classes. The streams can be input or output
streams. This class defines members that are independent of how the templates of the class are defined.

Page 2 of 12
istream Class − The istream class handles the input stream in c++ programming language. These input
stream objects are used to read and interpret the input as a sequence of characters. The cin handles the
input.

ostream class − The ostream class handles the output stream in c++ programming language. These
output stream objects are used to write data as a sequence of characters on the screen. cout and puts
handle the out streams in c++ programming language.

Example

#include <iostream>
using namespace std;
int main(){
cout<<"This output is printed on screen";
puts("This output is printed using puts");
int no;
cout<<"Enter a number ";
cin>>no;
cout<<"Number entered using cin is "<<no;
char ch[10];
puts("Enter a character array");
gets(ch);
puts("The character array entered using gets is : ");
puts(ch);
}

4.3 Stream Errors


std::cerr is an object of class ostream that represents the standard error stream oriented to narrow
characters (of type char). It corresponds to the C stream stderr. The standard error stream is a destination
of characters determined by the environment. This destination may be shared by more than one standard
object (such as cout or clog). As an object of class ostream, characters can be written to it either as
formatted data using the insertion operator (operator<<) or as unformatted data, using member functions
such as write. The object is declared in the header <iostream> with external linkage and static duration:
it lasts the entire duration of the program.

Example

#include<iostream>
int main() {
std::cerr << "Hello";
return 0;
}

Page 3 of 12
Output

Hello

4.4 File i/o with streams: C++ Read and Write Example
Let's see the simple example of writing the data to a text file testout.txt and then reading the data from
the file using C++ FileStream programming.

Example

#include <fstream>
#include <iostream>
using namespace std;
int main () {
char input[75];
ofstream os;
os.open("testout.txt");
cout <<"Writing to a text file:" << endl;
cout << "Please Enter your name: ";
cin.getline(input, 100);
os << input << endl;
cout << "Please Enter your age: ";
cin >> input;
cin.ignore();
os << input << endl;
os.close();
ifstream is;
string line;
is.open("testout.txt");
cout << "Reading from a text file:" << endl;
while (getline (is,line))
{
cout << line << endl;
}
is.close();
return 0;
}

Output

Writing to a text file:


Please Enter your name: Nakul Jain
Please Enter your age: 22
Reading from a text file: Nakul Jain
22

Page 4 of 12
4.5 File Pointers
There are few important functions to be used with file streams like:

 tellp() - It tells the current position of the put pointer.


Syntax: filepointer.tellp()
 tellg() - It tells the current position of the get pointer.
Syntax: filepointer.tellg()
 seekp() - It moves the put pointer to mentioned location.
Syntax: filepointer.seekp(no of bytes,reference mode)
 seekg() - It moves get pointer(input) to a specified location.
Syntax: filepointer.seekg((no of bytes,reference point)
 put() - It writes a single character to file.
 get() - It reads a single character from file.

Note: For seekp and seekg three reference points are passed: ios::beg - beginning of the file ios::cur -
current position in the file ios::end - end of the file

Example

#include <iostream>
#include<conio>
#include <fstream>
using namespace std;

int main()
{
fstream st; // Creating object of fstream class
st.open("E:\studytonight.txt",ios::out); // Creating new file
if(!st) // Checking whether file exist
{
cout<<"File creation failed";
}
else
{
cout<<"New file created"<<endl;
st<<"Hello Friends"; //Writing to file

// Checking the file pointer position


cout<<"File Pointer Position is "<<st.tellp()<<endl;

st.seekp(-1, ios::cur); // Go one position back from current position

Page 5 of 12
//Checking the file pointer position
cout<<"As per tellp File Pointer Position is "<<st.tellp()<<endl;
st.close(); // closing file
}
st.open("E:\studytonight.txt",ios::in); // Opening file in read mode
if(!st) //Checking whether file exist
{
cout<<"No such file";
}
else
{
char ch;
st.seekg(5, ios::beg); // Go to position 5 from begning.
cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl;
//Checking file pointer position
cout<<endl;
st.seekg(1, ios::cur); //Go to position 1 from beginning.
cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl;
//Checking file pointer position
st.close(); //Closing file
}
return 0;
}

Output

New file created


File Pointer Position is 13
As per tellp File Pointer Position is 12
As per tellg File Pointer Position is 5
As per tellg File Pointer Position is 6

4.6 Error Handling in File I/O


It is quite common that errors may occur while reading data from a file in C++ or writing data to a file. For
example, an error may arise due to the following:

1. When trying to read a file beyond indicator.

2. When trying to read a file that does not exist.

3. When trying to use a file that has not been opened.

Page 6 of 12
4. When trying to use a file in an inappropriate mode i.e., writing data to a file that has been opened
for reading.

5. When writing to a file that is write-protected i.e., trying to write to a read-only file.

Failure to check for errors then the program may behave abnormally therefore an unchecked error may
result in premature termination for the program or incorrect output.

Example: ferror():

// C++ program to illustrate the


// use of ferror()
#include <bits/stdc++.h>

// Driver Code
int main()
{
FILE* fp;
// If a file is opened which does not exist, then it will be an
// error and corresponding errno value will be set
char feedback[100];

int i;
fp = fopen("GeeksForGeeks.TXT", "w");

if (fp == NULL) {
printf("\n The file could "
"not be opened");
exit(1);
}

printf("\n Provide feedback on "


"this article: ");
fgets(feedback, 100, stdin);

for (i = 0; i < feedback[i]; i++)


fputc(feedback[i], fp);

// Error writing file


if (ferror(fp)) {
printf("\n Error writing in file");
exit(1);
}
// Close the file pointer
fclose(fp);
}

Page 7 of 12
Output

The function perror() stands for print error. In case of an error, the programmer can determine the type
of error that has occurred using the perror() function. When perror() is called, then it displays a message
describing the most recent error that occurred during a library function call or system call.

Example: clearerr():

// C++ program to illustrate the


// use of perror()
#include <bits/stdc++.h>
#include <errno.h>

// Driver Code
int main()
{
FILE* fp;

// First rename if there is any file


rename("file.txt", "newfile.txt");

// Now try to open same file


fp = fopen("file.txt", "r");

if (fp == NULL) {

perror("Error: ");
return (-1);
}

// Close the file pointer


fclose(fp);

return (0);
}

Page 8 of 12
Output

4.7 Overloading the extraction and insertion operators in c++


In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.
We must know the following things before we start overloading these operators.

1. cout is an object of ostream class and cin is an object of istream class.

2. These operators must be overloaded as a global function. And if we want to allow them to access
private data members of the class, we must make them friend.

Example

#include <iostream>
using namespace std;

class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);
};

ostream & operator << (ostream &out, const Complex &c)


{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}

istream & operator >> (istream &in, Complex &c)


{
cout << "Enter Real Part ";
in >> c.real;

Page 9 of 12
cout << "Enter Imaginary Part ";
in >> c.imag;
return in;
}

int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}

Output

Enter Real Part 10


Enter Imaginary Part 20
The complex object is 10+i20

4.8 Memory as a Stream Object


C++ Stream Objects- In this article you will learn how to use cin stream object and cout stream object
in C++ programming. Predefined C++ stream objects are used for basic input and output. A C++ stream
refers to a flow of data. The data may flow from the input device into the main memory or from the main
memory to the output device.

C++ provides various predefined C++ stream objects. The basic input/output C++ stream objects are cin,
cout, cerr, and clog. The cin object is associated with standard input and cout object is associated with
standard output. The cerr and clog both objects are linked to the standard output.

C++ input/output stream is declared in the header file “iostream.h”. in most of the c++ program, this
header file( iostream.h) must be included for the input and output of data.

Example: Write a program that inputs a character and displays its ASCII code using cin cout
stream objects

#include <iostream>
using namespace std;
main()
{
char ch;
int asc;

Page 10 of 12
cout<<"Enter the character: ";
cin>>ch;
asc=ch;
cout<<"ASCII code of "<<ch<<"is: " <<asc;
}

Output

Enter the character: B


ASCII code of B is 66
1
2
3
Output:
Enter the character: B
ASCII code of B is 66

4.9 Command-Line Arguments


It is possible to pass some values from the command line to your C programs when they are executed.
These values are called command line arguments and many times they are important for your program
especially when you want to control your program from outside instead of hard coding those values inside
the code.

The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to the
program. Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly −

Example

#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}

Page 11 of 12
Output

$./a.out "testing1 testing2"


Progranm name ./a.out
The argument supplied is testing1 testing2

Page 12 of 12

You might also like