Oop Notes Unit 4
Oop Notes Unit 4
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:
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);
}
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
Page 4 of 12
4.5 File Pointers
There are few important functions to be used with file streams like:
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
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
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():
// 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);
}
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():
// Driver Code
int main()
{
FILE* fp;
if (fp == NULL) {
perror("Error: ");
return (-1);
}
return (0);
}
Page 8 of 12
Output
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);
};
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
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
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
Page 12 of 12