0% found this document useful (0 votes)
11 views19 pages

Unit-5 CC

This document covers file stream operations in C++ including opening, closing, reading, and writing files using stream classes such as ofstream, ifstream, and fstream. It also discusses file pointers, error handling, command line arguments, templates, and exception handling. Additionally, it explains binary files, ASCII files, and the concept of random access files with examples and code snippets.

Uploaded by

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

Unit-5 CC

This document covers file stream operations in C++ including opening, closing, reading, and writing files using stream classes such as ofstream, ifstream, and fstream. It also discusses file pointers, error handling, command line arguments, templates, and exception handling. Additionally, it explains binary files, ASCII files, and the concept of random access files with examples and code snippets.

Uploaded by

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

DEPARTMENT OF B.

Com IT

CLASS: II B.Com IT SUBJECT : PROGRAMMING C++


UNIT –V

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.

To combine two or more of these values by OR


ing them together. For example if you want to open a file in write mo

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.

Reading from a File


To read information from a file into your program using the stream extraction
operator (>>) just as you use that operator to input information from the keyboard.
The only difference is that you use an ifstream or fstream object instead of
the cin object.

Read and Write Example

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];

// open a file in write mode.


ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;


cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

/* cout << "Enter your age: ";


cin >> data;
cin.ignore(); */

// again write inputted data into the file.


outfile << data << endl;
// close the opened file.
outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;


infile >> data;

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

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.

File Position Pointers


Both istream and ostream provide member functions for repositioning the file-
position pointer. These member functions are seekg ("seek get") for istream
and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument
can be specified to indicate the seek direction. The seek direction can
be ios::beg (the default) for positioning relative to the beginning of a
stream, ios::cur for positioning relative to the current position in a stream
or ios::end for positioning relative to the end of a stream.

The file-position pointer is an integer value that specifies the location in the file as a number of bytes from th

// position to the nth byte of fileObject (assumes ios::beg)


fileObject.seekg( n );

// position n bytes forward in fileObject


fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );

// position at end of fileObject


fileObject.seekg( 0, ios::end );

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

Step 1: Enter the following code in your favorite text editor.

#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>

using namespace std;


int main() {

ifstream f("a.txt"); //taking file as inputstream

string str;

if(f) {

ostringstream ss;

ss << f.rdbuf(); // reading data

str = ss.str();

cout<<str;

Difference between Binary Code and ASCII?


1) Binary code is a general term used for a method of encoding characters or
instructions, but ASCII is only one of the globally accepted conventions of encoding
characters and was the most commonly used binary encoding scheme for more than
three decades.
2) Binary code can have different lengths for encoding depending on the number of
characters, instructions, or the encoding method, but ASCII uses only 7 digits long
binary string and 8 digits long for extended ASCII.

Random Access Files

The file pointer


Each file stream class contains a file pointer that is used to keep track of the current
read/write position within the file. When something is read from or written to a file,
the reading/writing happens at the file pointer’s current location. By default, when
opening a file for reading or writing, the file pointer is set to the beginning of the file.
However, if a file is opened in append mode, the file pointer is moved to the end of
the file, so that writing does not overwrite any of the current contents of the file.
Random file access with seekg() and seekp()
So far, all of the file access we’ve done has been sequential -- that is, we’ve read or
written the file contents in order. However, it is also possible to do random file
access -- that is, skip around to various points in the file to read its contents. This
can be useful when your file is full of records, and you wish to retrieve a specific
record. Rather than reading all of the records until you get to the one you want, you
can skip directly to the record you wish to retrieve.
Random file access is done by manipulating the file pointer using either seekg()
function (for input) and seekp() function (for output). In case you are wondering, the
g stands for “get” and the p for “put”. For some types of streams, seekg() (changing
the read position) and seekp() (changing the write position) operate independently --
however, with file streams, the read and write position are always identical, so seekg
and seekp can be used interchangeably.
The seekg() and seekp() functions take two parameters. The first parameter is an
offset that determines how many bytes to move the file pointer. The second
parameter is an Ios flag that specifies what the offset parameter should be offset
from.
Example

int main()
{
std::ifstream inf{ "Sample.dat" };

// If we couldn't open the input file stream for reading


if (!inf)
{
// Print an error and exit
std::cerr << "Uh oh, Sample.dat could not be opened for reading!\n";
return 1;
}

std::string strData;

inf.seekg(5); // move to 5th character


// Get the rest of the line and print it
getline(inf, strData);
std::cout << strData << '\n';

inf.seekg(8, ios::cur); // move 8 more bytes into file


// Get rest of the line and print it
std::getline(inf, strData);
std::cout << strData << '\n';

inf.seekg(-15, ios::end); // move 15 bytes before end of file


// Get rest of the line and print it
std::getline(inf, strData);
std::cout << strData << '\n';
return 0;
Template
A template is a simple and yet very powerful tool in C++. The simple idea is to
pass data type as a parameter so that we don’t need to write the same code
for different data types. For example, a software company may need sort() for
different data types. Rather than writing and maintaining the multiple codes,
we can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’.
The second keyword can always be replaced by keyword ‘class’.

How do templates work?


Templates are expanded at compiler time. This is like macros. The difference
is, the compiler does type checking before template expansion. The idea is
simple, source code contains only function/class, but compiled code may
contain multiple copies of same function/class.
The need for function templates
In previous chapters, you’ve learned how to write functions and classes that help
make programs easier to write, safer, and more maintainable. While functions and
classes are powerful and flexible tools for effective programming, in certain cases
they can also be somewhat limiting because of C++’s requirement that you specify
the type of all parameters.
For example,

#include <iostream>

using namespace std;

// 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;

template <typename T>


class Array {
private:
T *ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T>
Array<T>::Array(T arr[], int s) {
ptr = new T[s];
size = s;
for(int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T>
void Array<T>::print() {
for (int i = 0; i < size; i++)
cout<<" "<<*(ptr + i);
cout<<endl;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
Array<int> a(arr, 5);
a.print();
return 0;
}
Exception Handling

An exception is a problem that arises during the execution of a program. A C++


exception is a response to an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
● throw
throw keyword.
● catch
place in a program where you want to handle the problem.
catch keyword indicates the catching of an exception.
● try try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch

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.

Following is an example of throwing an exception when dividing by zero condition occurs

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions
The catch block following the try block catches any exception. You can specify
what type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName

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;

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

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++.

C++ String Functions

Function Description

int compare(const string& str) It is used to compare two string objects.

int length() It is used to find the length of the string.

void swap(string& str) It is used to swap the values of two string


objects.

string substr(int pos,int n) It creates a new string object of n characters.

int size() It returns the length of the string in terms of


bytes.

void resize(int n) It is used to resize the length of the string up to


n characters.

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.

string& insert() It inserts a new character before the character


indicated by the position pos.

int max_size() It finds the maximum length of the string.

void push_back(char ch) It adds a new character ch at the end of the


string.

void pop_back() It removes a last character of the string.

string& assign() It assigns new value to the string.

int copy(string& str) It copies the contents of string into another.

char& back() It returns the reference of last character.

Iterator begin() It returns the reference of first character.

int capacity() It returns the allocated space for the string.

const_iterator cbegin() It points to the first element of the string.

const_iterator cend() It points to the last element of the string.

void clear() It removes all the elements from the string.

const_reverse_iterator crbegin() It points to the last character of the string.


const_char* data() It copies the characters of string into an array.

bool empty() It checks whether the string is empty or not.

string& erase() It removes the characters as specified.

char& front() It returns a reference of the first character.

string& operator+=() It appends a new character at the end of the


string.

string& operator=() It assigns a new value to the string.

char operator[](pos) It retrieves a character at specified position


pos.

int rfind() It searches for the last occurrence of the string.

iterator end() It references the last character of the string.

reverse_iterator rend() It points to the first character of the string.

void shrink_to_fit() It reduces the capacity and makes it equal to


the size of the string.

char* c_str() It returns pointer to an array that contains null


terminated sequence of characters.

const_reverse_iterator crend() It references the first character of the string.

reverse_iterator rbegin() It reference the last character of the string.

void reserve(inr len) It requests a change in capacity.

allocator_type get_allocator(); It returns the allocated object associated with


the string.

In C++, string is an object of std::string class that represents sequence of


characters. We can perform many operations on strings such as concatenation,
comparison, conversion etc.
C++ String Example
Let's see the simple example of C++ string.

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:

C++ String Compare Example


let's see the simple example of string comparison using strcmp() function.

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. }

C++ String Concat Example


Let's see the simple example of string concatenation using strcat() function.

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. }

C++ String Copy Example


Let's see the simple example of copy the string using strcpy() function.

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. }

C++ String Length Example


Let's see the simple example of finding the string length using strlen() function.

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. }

You might also like