UNIT 4
Files and Streams
1. What are the Facilities provided by these stream classes explain in detail with some examples?
Example:
#include <iostream> using namespace std;
int main() { char x;
// used to scan a single char cin.get(x);
cout << x; } |
Input:
g
Output:
g
3. The ostream class: This class is responsible for handling output stream. It provides number of function for handling chars, strings and objects such as write, put etc..
Example:
#include <iostream> using namespace std;
int main() { char x;
// used to scan a single char cin.get(x);
// used to put a single char onto the screen. cout.put(x); } |
Input:
g
Output:
g
4. The iostream: This class is responsible for handling both input and output stream as both istream class and istream class is inherited into it. It provides function of both istream class and istream class for handling chars, strings and objects such as get, getline, read, ignore, putback, put, write etc..
Example:
#include <iostream> using namespace std;
int main() {
// this function display // ncount character from array cout.write("geeksforgeeks", 5); } |
Output:
geeks
5. istream_withassign class: This class is variant of istream that allows object assigment. The predefined object cin is an object of this class and thus may be reassigned at run time to a different istream object.
Example:To show that cin is object of istream class.
#include <iostream> using namespace std;
class demo { public: int dx, dy;
// operator overloading using friend function friend void operator>>(demo& d, istream& mycin) { // cin assigned to another object mycin mycin >> d.dx >> d.dy; } };
int main() { demo d; cout << "Enter two numbers dx and dy\n";
// calls operator >> function and // pass d and cin as reference d >> cin; // can also be written as operator >> (d, cin) ;
cout << "dx = " << d.dx << "\tdy = " << d.dy; } |
Input:
4 5
Output:
Enter two numbers dx and dy
4 5
dx = 4 dy = 5
6. ostream_withassign class: This class is variant of ostream that allows object assigment. The predefined objects cout, cerr, clog are objects of this class and thus may be reassigned at run time to a different ostream object.
Example:To show that cout is object of ostream class.
#include <iostream> using namespace std;
class demo { public: int dx, dy;
demo() { dx = 4; dy = 5; }
// operator overloading using friend function friend void operator<<(demo& d, ostream& mycout) { // cout assigned to another object mycout mycout << "Value of dx and dy are \n"; mycout << d.dx << " " << d.dy; } };
int main() { demo d; // default constructor is called
// calls operator << function and // pass d and cout as reference d << cout; // can also be written as operator << (d, cin) ; } |
Output:
Value of dx and dy are
4 5
2. Write File Stream example: writing to a file
Let's see the simple example of writing to a text file testout.txt using C++ FileStream programming.
Output:
The content of a text file testout.txt is set with the data:
Welcome to javaTpoint.
C++ Tutorial.
3. Write FileStream example: reading from a file
Let's see the simple example of reading from a text file testout.txt using C++ FileStream programming.
Note: Before running the code a text file named as "testout.txt" is need to be created and the content of a text file is given below:
Welcome to javaTpoint.
C++ Tutorial.
Output:
Welcome to javaTpoint.
C++ Tutorial.
4. Write a program of Read and Write
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.
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
5. Give some examples of stream classes
Example
OUT STREAMCOUT
#include <iostream>
using namespace std;
int main(){
cout<<"This output is printed on screen";
}
Output
This output is printed on screen
PUTS
#include <iostream>
using namespace std;
int main(){
puts("This output is printed using puts");
}
Output
This output is printed using puts
IN STREAMCIN
#include <iostream>
using namespace std;
int main(){
int no;
cout<<"Enter a number ";
cin>>no;
cout<<"Number entered using cin is "<
Output
Enter a number 3453
Number entered using cin is 3453
gets
#include <iostream>
using namespace std;
int main(){
char ch[10];
puts("Enter a character array");
gets(ch);
puts("The character array entered using gets is : ");
puts(ch);
}
Output
Enter a character array
thdgf
The character array entered using gets is :
thdgf
6. Explain Stream errors with examples
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.
You can use this object to write to the screen. For example, if you want to write "Hello" to the screen, you'd write −
Example
#include<iostream>
int main() {
std::cerr << "Hello";
return 0;
}
Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using −
$ g++ hello.cpp
Run it using −
$ ./a.out
Output
This will give the output −
Hello
7. Explain open file in Disk File I/O with Streams with examples
Open a file
The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream (i.e., an object of one of these classes; in the previous example, this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.
In order to open a file with a stream object we use its member function open:
open (filename, mode);
Where filename is a string representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:
ios::in | Open for input operations. |
ios::out | Open for output operations. |
ios::binary | Open in binary mode. |
ios::ate | Set the initial position at the end of the file. |
ios::app | All output operations are performed at the end of the file, appending the content to the current content of the file. |
ios::trunc | If the file is opened for output operations and it already existed, its previous content is deleted and replaced by the new one. |
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open:
1 | ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary); |
|
Each of the open member functions of classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:
class | default mode parameter |
ofstream | ios::out |
ifstream | ios::in |
fstream | ios::in | ios::out |
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open member function (the flags are combined).
For fstream, the default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).
Since the first task that is performed on a file stream is generally to open a file, these three classes include a constructor that automatically calls the open member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conduct the same opening operation in our previous example by writing:
| ofstream myfile ("example.bin", ios::out | ios::app | ios::binary); |
|
Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.
To check if a file stream was successful opening a file, you can do it by calling to member is_open. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:
| if (myfile.is_open()) { /* ok, proceed with output */ } |
|
8. Explain closing file in Disk File I/O with Streams with examples
Closing a file
When we are finished with our input and output operations on a file we shall close it so that the operating system is notified and its resources become available again. For that, we call the stream's member function close. This member function takes flushes the associated buffers and closes the file:
| myfile.close(); |
|
Once this member function is called, the stream object can be re-used to open another file, and the file is available again to be opened by other processes.
In case that an object is destroyed while still associated with an open file, the destructor automatically calls the member function close.
Text files
Text file streams are those where the ios::binary flag is not included in their opening mode. These files are designed to store text and thus all values that are input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.
Writing operations on text files are performed in the same way we operated with cout:
1 | // writing on a text file #include <iostream> #include <fstream> using namespace std;
int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; } | [file example.txt] This is a line. This is another line. |
|
Reading from a file can also be performed in the same way that we did with cin:
1 | // reading a text file #include <iostream> #include <fstream> #include <string> using namespace std;
int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << '\n'; } myfile.close(); }
else cout << "Unable to open file";
return 0; } | This is a line. This is another line. |
|
This last example reads a text file and prints out its content on the screen. We have created a while loop that reads the file line by line, using getline. The value returned by getline is a reference to the stream object itself, which when evaluated as a boolean expression (as in this while-loop) is true if the stream is ready for more operations, and false if either the end of the file has been reached or if some other error occurred.
9. Explain file pointers with examples
Read Mode
Fig.: Get pointer in read mode
Write mode
Fig.: Put pointer in write mode
Append Mode
Fig. : Get pointer in append mode
In append mode put pointer is set at the end of file.
Program
Program to append a file.
#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
clrscr();
{
ofstream fout;
char X[50];
fout.open(“Demo”, ios::out);
cout<<”Enter text”<<endl;
cin.getline(X,50);
fout<<X;
fout.close();
fout.open(“Demo”, ios::app);
cout<<”\n Enter text again”<<endl;
cin.getline(X,50);
fout<<X;
fout.close();
ifstream fin;
fin.open(“Demo”, ios::in);
cout<<”/n Contents of file”;
while(fin.eof==0)
{
fin>>data;
cout<<data;
}
return 0;
}
10. Explain Error Handling in File I/O
Function | Meaning |
int bad() | Returns true (non zero value) if invalid operation or unrecoverable error is encountered and false(zero) for recoverable error. |
int eof() | Returns true if end of file is encountered otherwise false. |
int good() | Returns true if no error is encountered otherwise false. |
fail() | Returns true if input/output operation has failed. |
clear() | Resets the error state so that further operations can be attempted. |
ifstream fin;
fin.open("master", ios::in);
while(!fin.fail())
{
: // process the file
}
if(fin.eof())
{
: // terminate the program
}
else if(fin.bad())
{
: // report fatal error
}
else
{
fin.clear(); // clear error-state flags
:
}
ifstream fin(“demo.txt”);
if(!fin)
cout<<”File not found”;
ifstream fin(“demo.txt”);
while(!fin.eof())
{
Read data;
Write data;
}