0% found this document useful (0 votes)
15 views16 pages

Unit-5 Remaining Notes

The document discusses file modes and pointers in C++, detailing how to manipulate file pointers for reading and writing data. It explains the three file modes (read, write, append) and provides examples of sequential input/output operations, updating files, and exception handling. Additionally, it covers command-line arguments and how to process them in a C++ program.

Uploaded by

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

Unit-5 Remaining Notes

The document discusses file modes and pointers in C++, detailing how to manipulate file pointers for reading and writing data. It explains the three file modes (read, write, append) and provides examples of sequential input/output operations, updating files, and exception handling. Additionally, it covers command-line arguments and how to process them in a C++ program.

Uploaded by

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

FILE MODES:

FILE POINTERS AND THEIR MANIPULATIONS:

Each file has two associated pointers known as the file pointers. One of them is
called the input pointer and the other is called the output pointer.

We use these pointers to move through files while reading or writing

Each time an input or output operation takes place, appropriate pointer is


automatically advanced.
ifstream, like istream, has a pointer known as get pointer that points to
the element to be read in the next input operation.

ofstream, like ostream, has a pointer known as put pointer that points to
the location where the next element has to be written.

There are three modes under which we can open a file:

o Read only mode

o Write only mode

o Append mode

When we open a file in read only mode, the input pointer is


automatically set at the beginning so that we read the file from the
beginning.

When we open a file in write only mode, the existing contents are
deleted and output pointer is set at the beginning

If we want to open an existing file to add more data, the file is opened
in append mode. This moves the file pointer to the end of the file.

FUNCTIONS FOR MANIPULATION OF FILE POINTERS:


SEQUENTIAL INPUT AND OUTPUT OPERATIONS:

The file stream class support a number of member functions for


performing the input and output operations on files.

▫ put() and get() : used for handling a single character.


▫ read() and write() : used for handling large blocks of binary data

EXAMPLE: 12TH PRACTICAL PROGRAM

Reading & Writing a class object:

• C cannot handle user defined data types such as class objects.

• C++ provides read() and write() functions to read and write the objects
directly.

• The length of the object is obtained using the sizeof operator.

• This length represents the sum total of lengths of all data members of
the object.

Syntax:

▫ infile.read ((char *) & V, sizeof (V));

▫ outfile.write ((char *) & V, sizeof (V));

• The first argument is the address of the variable V.


• The second is the length of that variable in bytes.

• The address of the variable must type cast to char *

(ie: pointer to character type).

Example

#include<iostream.h>

#include<fstream.h>

class inventory

char name[10];

int code;

float cost;

public:

void readdata(void);

void writedata(void);

};

void inventory :: readdata(void)

cout<<“Enter name:”;

cin>> name;

cout<<“Enter code:”;

cin>>code;

cout<<“Enter cost:”;

cin>> cost;

}
void inventory :: writedata(void)

cout<<name;

cout<<code;

cout<<cost;

int main()

inventory item[3];

fstream file;

file.open(“Stock.dat”, ios::in | ios::out);

cout<<“Enter the details for three items:”;

for(int i=0; i<3;i++)

item[i].readdata();

file.write((char *) & item[i], sizeof(item[i]));

file.seekg(0);

for(i=0;i<3;i++)

file.read((char *) & item[i], sizeof(item[i]));

item[i].writedata();

file.close();
return 0;

Updating a File: Random Access


Updating is a routine task in the maintenance of any data file.

The updating would include one or more of the following tasks:

• Displaying the contents of a file.

• Modifying an existing item.

• Adding a new item.

• Deleting an existing item.

Example:

#include<iostream.h>

#include<fstream.h>

class inventory

char name[10];

int code;

float cost;

public:

void getdata(void)

cout<<“Enter name : ” ; cin>> name;

cout<<“Enter code : ” ; cin>>code;

cout<<“Enter cost : ” ; cin>> cost;


}

void putdata(void)

cout<<name;

cout<<code;

cout<<cost;

};

int main()

inventory item;

fstream inoutfile;

inoutfile.open(“stock.dat”, ios::ate | ios::in | ios::out|

ios::binary);

inoutfile.seekg(0, ios::beg);

while(inoutfile.read((char * ) & item, sizeof item))

item.putdata();

inoutfile.clear(); //turn off EOF flag

cout<<“Add an item:”;

item.getdata();

inoutfile.write((char * ) & item, sizeof item);

inoutfile.seekg(0);
while(inoutfile.read((char * ) & item, sizeof item))

item.putdata();

int last = inoutfile.tellg(); // finds the no. of objects

int n = last/sizeof(item);

cout<<“Number of objects:”<<n;

cout<<“Enter the object number to be updated:”;

int object;

cin>> object;

int location = (object-1)* sizeof(item);

inoutfile.seekp(location);

inoutfile.seekg(0);

cout<<“Contents of updated file are:”;

while(inoutfile.read((char * ) & item, sizeof item))

item.putdata();

inoutfile.close();

return 0;

Output:

current contents of stock:

AA 11 100
BB 22 200

CC 33 300

Add an item:

Enter name: DD

Enter code: 44

Enter cost: 400

Contents of Appended file:

AA 11 100

BB 22 200

CC 33 300

DD 44 400

Number of objects: 4

Enter the object to be updated: 4

Enter new values for object:

Enter name: EE

Enter code: 55

Enter cost: 500

Contents of updated file:

AA 11 100

BB 22 200

CC 33 300

EE 55 500

Exception Handling in C++


Exceptions are runtime anomalies that a program encounters during execution.
Exception includes condition such as division by zero, accessing an array outside its
bound, running out of memory, etc.
In order to handle these exceptions, exception handling mechanism is used which
identifies and deal with such condition. Exception handling mechanism consists of
following parts:

1. Find the problem (Hit the exception)


2. Inform about its occurrence (Throw the exception)
3. Receive error information (Catch the exception)
4. Take proper action (Handle the exception)

C++ consists of 3 keywords for handling the exception. They are

1. try: Try block consists of the code that may generate exception. Exception are
thrown from inside the try block.
2. throw: Throw keyword is used to throw an exception encountered inside try
block. After the exception is thrown, the control is transferred to catch block.
3. catch: Catch block catches the exception thrown by throw statement from try
block. Then, exception are handled inside catch block.

Syntax
try
{
statements;
... ... ...
throw exception;
}

catch (type argument)


{
statements;
... ... ...
}

Multiple catch exception


Multiple catch exception statements are used when a user wants to handle different
exceptions differently. For this, a user must include catch statements with different
declaration.

Syntax
try
{
body of try block
}

catch (type1 argument1)


{
statements;
... ... ...
}

catch (type2 argument2)


{
statements;
... ... ...
}
... ... ...
... ... ...
catch (typeN argumentN)
{
statements;
... ... ...
}

Catch all exceptions


Sometimes, it may not be possible to design a separate catch block for each kind of
exception. In such cases, we can use a single catch statement that catches all kinds of
exceptions.

Syntax
catch (...)
{
statements;
... ... ...
}

Note: A better way is to use catch(...) as a default statement along with other catch
statement so that it can catch all those exception which are not handled by other catch
statements.

Example of exception handling


C++ program to divide two numbers using try catch block.
#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
int a,b;
cout << "Enter 2 numbers: ";
cin >> a >> b;
try
{
if (b != 0)
{
float div = (float)a/b;
if (div < 0)
throw 'e';
cout << "a/b = " << div;
}
else
throw e;

}
catch (int e)
{
cout << "Exception: Division by zero";
}
catch (char st)
{
cout << "Exception: Division is less than 1";
}
catch(...)
{
cout << "Exception: Unknown";
}
getch();
return 0;
}

This program demonstrate how exception are handled in C++. This program performs
division operation. Two numbers are entered by user for division operation. If the
dividend is zero, then division by zero will cause exception which is thrown into catch
block. If the answer is less than 0, then exception "Division is less than 1" is thrown.
All other exceptions are handled by the last catch block throwing "Unknown"
exception.

Output
Enter 2 numbers: 8 5
a/b = 1.6

Enter 2 numbers: 9 0
Exception: Division by zero

Enter 2 numbers: -1 10
Exception: Division is less than 1

Command line argument:


Command-line arguments are values supplied from the command line, after the C++ program name.
C++ language allows the user to specify values on the command line when the program is run so that
it is easy to alter the runtime behavior of the program.

main() function
We can process the command line arguments using the below main function with arguments
as:

int main(int argc, char* argv[])


{
//C++ code
}

argc
This argument is the count of the arguments. It tells how many command-line arguments
were passed.

argv[]
This argument represents an array of pointers to an array of strings.

Ex:

#include<iostream>
using namespace std;

int main(int argc, char *argv[])


{
cout << "Number of command line arguments[This includes program path] = "
<< argc << endl;
for(int i=0;i< argc;i++)
cout << argv[i] << endl;
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy