Unit-5 CC
Unit-5 CC
Com IT
Files – Classes for file stream Operations – opening, closing and processing files
– End of file Detection – File pointers – Updating a file – Error Handling during file
Operations – Command line Arguments – Templates – Exception Handling.
STREAM CLASSES
It have been using the iostream standard library, which
provides cin and cout methods for reading from standard input and writing to
standard output respectively.
In C++ ,the stream classes are used , how to read and write from a file. This
requires another standard C++ library called fstream
, which defines three new data types
Sr.No Data Type & Description
1 ofstream
This data type represents the output file stream and is used to create files and
to write information to files.
2 ifstream
This data type represents the input file stream and is used to read information
from files.
3 fstream
This data type represents the file stream generally, and has the capabilities of
both ofstream and ifstream which means it 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 a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And
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.
Sr.No Mode Flag & Description
1 ios::app
Append mode. All output to that file to be appended to the end.
2 ios::ate
Open a file for output and move the read/write control to the end of the file.
3 ios::in
Open a file for reading.
4 ios::out
Open a file for writing.
5 ios::trunc
If the file already exists, its contents will be truncated before opening the file.
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically 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.
void close();
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.
Following is the C++ program which opens a file in reading and writing mode. After writing information ent
Live Demo
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
When the above code is compiled and executed, it produces the following sample input and output
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline()
function to read the line from outside and ignore() function to ignore the extra
characters left by previous read statement.
The file-position pointer is an integer value that specifies the location in the file as a number of bytes from th
Binary files
Text files are not the only type of flat files you can use. You can also use binary files.
Binary files are still flat files; however, they are in basic binary format rather than
ASCII. Remember that everything in a computer is binary (1’s and 0’s). The binary
format has each file stored in a byte-by-byte format. This produces some odd-looking
results if you try to view binary files like plain text. For example, an integer might be
represented by four separate characters, because it occupies four bytes. You might
ask why anyone would want to open a binary file. There are a number of reasons,
the most prominent being that there is still old data stored this way. However, one
useful thing you can do is to open any file in binary mode and count the bytes in it, to
see how big the file is. This next example demonstrates this.
Example 6.5
#include <iostream>
using namespace std;
#include <fstream>
int main ()
{ long start,end; // Recall from chapter one, that a long is simply // large integers
ifstream myfile ("test.txt", ios::in|ios::binary);
start = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size of " << "test.txt";
cout << " is " << (end-start) << " bytes.\n";
return 0;
}
ASCII FILES
ASCII stands for American Standard Code for Information Interchange. A coded character
set consisting of 128 7-bit characters. There are 32 control characters, 94 graphic
characters, the space character, and the delete character. The ASCII protocol is made up of
data that is encoded in ASCII values with minimal control codes added. The control codes
that are added are interpreted by the printer. Parallel, Serial, and Ethernet medium all
support ASCII communication and consider it to be the standard. All computer files are
comprised of tiny pieces of information, called bits. In an ASCII file, each byte directly
correlates to a specific character as defined by the standard ASCII code. A common
example of an ASCII file is a text document created without any formatting, such as font
styles or paragraph indentations. An ASCII file is a binary file that stores ASCII codes. There
are 128 different ASCII codes; this means that only 7 bits are needed to represent an ASCII
character. So in any ASCII file, you’re wasting 1/8 of the bits. In particular, the most
significant bit of each byte is not being used. A full, general binary file has no such
restrictions. Any of the 256-bit patterns can be used in any byte of a binary file. ASCII files
are used for simple word editing, but they are also the basis for all web pages. HTML is
written in ASCII because each character has a specific and unique meaning that can be
easily read by web browsers.
Example
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
string str;
if(f) {
ostringstream ss;
str = ss.str();
cout<<str;
int main()
{
std::ifstream inf{ "Sample.dat" };
std::string strData;
#include <iostream>
// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
cout << myMax<char>('g', 'e') << endl; // call myMax for char
return 0;
}
Class Templates
Like function templates, class templates are useful when a class defines
something that is independent of the data type. Can be useful for classes like
LinkedList, BinaryTree, Stack, Queue, Array, etc.
Following is a simple example of template Array class.
#include <iostream>
using namespace std;
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can be
any expression and the type of the result of the expression determines the type of
exception thrown.
try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we
catch it in catch block.
Live Demo
#include <iostream>
using namespace std;
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
C++ Strings
C++ provides following two types of string representations
● The C-style character string.
● The string class type introduced with Standard C++.
Function Description
string& replace(int pos,int len,string& It replaces portion of the string that begins at
str) character position pos and spans len
characters.
string& append(const string& str) It adds new characters at the end of another
string object.
char& at(int pos) It is used to access an individual character at
specified position pos.
int find(string& str,int pos,int n) It is used to find the string specified in the
parameter.
int find_first_of(string& str,int pos,int It is used to find the first occurrence of the
n) specified sequence.
int find_first_not_of(string& str,int It is used to search the string for the first
pos,int n ) character that does not match with any of the
characters specified in the string.
int find_last_of(string& str,int pos,int It is used to search the string for the last
n) character of specified sequence.
int find_last_not_of(string& str,int It searches for the last character that does not
pos) match with the specified sequence.
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. string s1 = "Hello";
5. char ch[] = { 'C', '+', '+'};
6. string s2 = string(ch);
7. cout<<s1<<endl;
8. cout<<s2<<endl;
9. }
Output:
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main ()
5. {
6. char key[] = "mango";
7. char buffer[50];
8. do {
9. cout<<"What is my favourite fruit? ";
10. cin>>buffer;
11. } while (strcmp (key,buffer) != 0);
12. cout<<"Answer is correct!!"<<endl;
13. return 0;
14. }
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char key[25], buffer[25];
7. cout << "Enter the key string: ";
8. cin.getline(key, 25);
9. cout << "Enter the buffer string: ";
10. cin.getline(buffer, 25);
11. strcat(key, buffer);
12. cout << "Key = " << key << endl;
13. cout << "Buffer = " << buffer<<endl;
14. return 0;
15. }
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char key[25], buffer[25];
7. cout << "Enter the key string: ";
8. cin.getline(key, 25);
9. strcpy(buffer, key);
10. cout << "Key = "<< key << endl;
11. cout << "Buffer = "<< buffer<<endl;
12. return 0;
13. }
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char ary[] = "Welcome to C++ Programming";
7. cout << "Length of String = " << strlen(ary)<<endl;
8. return 0;
9. }