0% found this document useful (0 votes)
2 views

pointers_filehandling_2024

Chapter 11 discusses pointers in programming, explaining their definition, differences from normal variables, advantages, and memory allocation methods. It covers pointer arithmetic, operations on pointers, and the concept of dynamic memory allocation using 'new' and 'delete'. Chapter 12 focuses on data file handling in C++, detailing file operations, types of files, and various functions for input/output operations.

Uploaded by

tan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

pointers_filehandling_2024

Chapter 11 discusses pointers in programming, explaining their definition, differences from normal variables, advantages, and memory allocation methods. It covers pointer arithmetic, operations on pointers, and the concept of dynamic memory allocation using 'new' and 'delete'. Chapter 12 focuses on data file handling in C++, detailing file operations, types of files, and various functions for input/output operations.

Uploaded by

tan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CHAPTER 11: POINTERS

Pointer variable
A pointer variable is a variable that stores the memory address of another variable.

Differences between a normal variable and pointer variable

NORMAL VARIABLE POINTER VARIABLE

A variable stores the value A pointer variable stores the memory address
of another variable

The size of the normal variable The size of pointer variable is 2 bytes
depends on the data type irrespective of datatype

The variable name is used to Asterisk (*) is used with the variable for data
access the value access

Used for static memory Used for dynamic memory allocation


allocation

Advantages
 It is possible to write efficient programs.

 Memory is utilized properly.


 Dynamically allocation & de-allocation of memory.

 Used for creating complex data structures such as stacks, queues, linked list etc.
 Establishes communication between program and data.
Declaration of pointer
The general form is

datatype *pointervariablename;

Example

int *ptr;
Pointer initialization

Syntax
pointervariable = &variable;

Example
int n;

int *ptr;
n=10;
ptr = &n;

THE ADDRESS-OF OPERATOR (&) OR REFERENCE OPERATOR


& is a unary operator that returns the memory address of its operand. For
example, if ‘n’ is an integer variable, then &n is its address.

Example
int n= 25;

int *ptr;
ptr = &n;

POINTER OPERATOR OR INDIRECTION OPERATOR OR DEREFERENCE


OPERATOR (*)
* is the complement of &.It is a unary operator that returns the value of the variable located at
the address specified by its operand.

Direct addressing
Accessing the variable in one step by using the variable name.
Example
int n;

cin>>n;

Indirect addressing
Accessing a variable in two steps - first using a pointer that gives the location of the
variable and then accessing the variable using the location.

Example
int n;
int *ptr;

ptr = &n;
cin>>*ptr;

Pointer arithmetic
Pointer is an address which is a numeric value.

Operations on pointers
 We can add an integer value to a pointer.
 We can subtract an integer value from a pointer.

 We can compare two pointers, if they point the elements of the same array.
 We can subtract one pointer from another pointer if both point to the same array.

 We can assign one pointer to another pointer provided both are of same type.

Following operations cannot be performed on pointers


 Addition of two pointers(ptr = ptr1+ptr2)
 Subtraction of one pointer from another pointer (ptr = ptr1-ptr2)

 Multiplication of two pointers(ptr = ptr1*ptr2)


 Division of two pointers(ptr = ptr1/ptr2)

Array of pointers
Array of pointers means collection of addresses.

Syntax
datatype *arrayname[size];

Example
int *ptr[3];
int i=10, j=20, k=30;

ptr[0] = &i; *ptr[0] = 10;


ptr[1] = &j; *ptr[1] = 20;

ptr[2] = &k; *ptr[2] = 30;

Memory allocation of pointers (Dynamic and Static)


Every data and instructions that is being executed must be allocated some space in the memory.
Memory allocation is done in two ways:

 Static allocation
 Dynamic allocation
Static allocation of memory
Allocating memory during compilation is called static memory allocation.
Example
int a;

Allocates 2 bytes of memory space during the compilation time.

Dynamic allocation of memory (new and delete)


The allocation of memory during run-time is called as dynamic memory
allocation. It has two operators - new and delete.

New operator
It is used for dynamic allocation of memory.

Syntax
pointervariable = new datatype;

Example
int *ptr;
ptr = new int;

The first statement declares the pointer ‘ptr’. The second


statement then allocates memory for an integer and then makes ‘ptr’
point to the new memory.

Delete
It is used for dynamic deallocation of memory.

Syntax
delete pointervariable;

delete ptr;

Static allocation of memory Dynamic allocation of memory

The amount of memory to be allocated is The amount of memory to be allocated is not


predicted and pre-known. known.
Memory is allocated during Memory is allocated during the execution of the
Compilation(before the execution of the program.
program)

No memory allocation or de-allocation are Memory allocation and de-allocation are


performed during Execution. established during the Execution.

Variables remain permanently allocated. Allocated only when program unit is active.

Implemented using stacks. Implemented using heaps.

Waste of memory space. No waste of memory space.

Free store(heap memory)


Free store is a pool of unallocated memory heap given to a program that is used by the program
for dynamic allocation during execution.

Memory Leak
These orphaned memory blocks when increase in number, cause adverse effect on the system.
This situation is called memory leak.

this pointer
Every object of a class maintains a hidden pointer to itself called as ‘this’ pointer.

CHAPTER 12:DATA FILE HANDLING


In C++,the unformatted and formatted I/O operations are implemented through
iostream library.
In C++, I/O occurs in streams, which are sequences of bytes.

If bytes flow from a device like a keyboard, a disk drive etc. to main memory, it
is called input operation.
If bytes flow from main memory to a device like a display screen, a printer etc., it
is called output operation.
The information/data stored under a specific name on a storage device, is called a file. File
operations are implemented through a header fstream.h.

The stream that supplies data to the program is known as input stream. It
reads the data from the file and hand it over to the program.
The stream that receives data from the program is known as output stream.
It writes the received data to the file.

CLASSES FOR FILE STREAM OPERATION

Classes Functions

fstreambase It combines all file streams. It acts as a common base to fstream,


ifstream and ofstream classes. It contains open() and close()
functions.

ifstream It creates file object for input operation. It helps to read data from a
file. It provides get( ), getline( ),read( ) ,seekg( ) and tellg( ) functions.

ofstream It creates file object for output operation. It helps to write data into a
file. It provides put( ), write( ) ,seekp( ) and tellp () functions.

fstream It provides simultaneous read and write operation. It supports all the
functions of istream, ostream and iostream objects.

Types of data Files


Files are classified into two types - Text file and Binary file.

Text file
It is a file that stores information in ASCII characters. In text files, each line of
text is terminated with a special character known as EOL (End- of-line) character or delimiter
character. When this EOL character is read or written, certain internal translations take place.

Binary file
It is a file that contains information in the binary form. In binary files, no
delimiters are used for a line and no translations occur . These files are faster and easier for
programming to read and write data or information.
Opening and closing files
In C++, while opening a file, we need the stream like input, output and
input/output. To create an input stream you must declare the stream to be of class ‘ifstream’. To
create an output stream you must declare the stream to be of class ‘ofstream’. Streams that will
be performing both input and output operations must be declared as class ‘fstream’.
Opening a file can be accomplished in two ways:

 using constructor
 using open( ) member function

The first method is preferred when a single file is used with a stream. For
managing multiple files with the same stream, the second method is preferred.

Opening file using constructor


The syntax of opening a file for output purpose only using an object of ‘ofstream’
class and the constructor is as follows:
ofstream ofstream_object(“file_name”);

Example
ofstream fout(“example.txt”);
‘fout’ is declared to be an object of ‘ofstream’ type and it is
made to represent the file ‘example.txt’ opened for output purpose only.

The syntax of opening a file for input purpose only using an object of ‘ifstream’ class and the
constructor is as follows.
ifstream ifstream_object(“file_name”);

Example
ifstream fin(“example.txt”);

Opening file using open( )


The syntax for opening a file for output purpose using an object of
‘ofstream’ class and open( ) member function is as follows:
ofstream_object.open(“filename”);
Example
ofstream ofile;
ofile.open(“example.txt”);

The syntax for opening a file for input purpose only using an object of ‘ifstream’ class and open(
) member function is as follows:

ifstream_object.open(“filename”);
ifstream-object is an object of type ifstream and “file
name” is any valid name of a file to be opened for input purpose only.

Example
ifstream ifile;

ifile.open(“example.txt”);

The syntax for opening a file using an object of type fstream class and the
constructor is as follows:
fstream fstream-object(“filename", mode);

The syntax for opening a file using an object of type fstream class and the
open() member function is as follows:
fstream_object.open(“filename”,mode);

Concepts of file modes

File mode parameter Meaning

ios::app Add data at the end of file.


ios::in Opens a file for input operation.

ios::out Opens a file for output operation.

ios::ate Sets the initial position at the end of the file.


Otherwise the initial position is the beginning of the
file.

ios::binary Opens a file in binary mode.

ios::trunk On opening, delete the contents of file.

All these flags can be combined using the bitwise operator OR ( | ).

Example
1) fstream fout(“example.txt”, ios::out);
open ‘example.txt’ in output mode

2) fstream fin(“example.txt”, ios::in);


open ‘example.txt’ in input mode
3) fstream file;
file.open (“example.bin”, ios::app | ios::binary);
The file “example.bin” will be opened in binary mode to add
data.

Closing File
The close() function removes the linkage between the file and the stream object.

Syntax
stream_object. close();

Example
fout.close();
fin.close();

Input and output operations in text files


Text files have get() and put() as character input and output
operations.

get()
The get() member function belongs to the class ‘ifstream’ and the function get()
reads a single character from the associated stream.

Syntax
ifstream_object.get(ch);
where ‘ch’ is a character constant or a character variable. The function
reads ‘ch’ from the file represented by the ‘ifstream_object’ into the variable ‘ch’.

Example
char ch ;

ifstream fin(“example.txt”);
fin.get(ch);

It reads a character into the variable ‘ch’ from the file represented by the
object ‘fin’. i.e., ‘example.txt’.

put()
The put() member function belongs to the class ofstream and writes a single character to
the associated stream.

Syntax
ofstream_object.put(ch);
where ‘ch’ is a character constant or a character variable. This function
writes ‘ch’ onto the file represented by ‘ofstream_object’.

Example
char ch = ‘a’;

ofstream fout(“example.txt”);
fout.put(ch);
This writes the character stored in ‘ch’(character ‘a’) onto the file represented by
the object ‘fout’. i.e., ‘example.txt’.

String I/O
The getline() function
It is used to read a whole line of text. It belongs to the class ‘ifstream’.

Syntax
ifstream_object.getline(arrayname, SIZE);

Example
char book[100];
ifstream fin;

fin.getline(book, 25);
Reads 25 characters from the file represented by the object ‘fin’.

Basic operation on binary file in C++


• Creating a file

• Searching a particular data


• Appending data to a file

• Reading data from a file

• Writing data into a file


• Deleting the data from a file

• Modifying data in a file

Input and output operation in binary files


The binary files help optimize storage space and file I/O would be faster when
compared to text files.

read() and write() member functions are used for input and
output operations.
Detecting end of file
An end of file is detected by using the member function eof(). eof() returns true
(non-zero) if end-of-file is encountered while reading, otherwise returns false(zero).

Syntax
while(!ifstream_object.eof())
{

statements;
}

Example
while (!fin.eof())

{
statements;

}
This is used to execute set of statements as long as the end of the file represented
by the object ‘fin’ is not reached.

seekg()
There are two types –

• seekg(long);

• seekg(offset, seekdir);
seekg(long);
The seekg(long) moves the get pointer to a specified location from the beginning
of a file.

Example
fin.seekg(20) ;
The get pointer points to 20th byte in the file.

seekg(offset, seekdir);
The offset indicates the number of bytes the get pointer is to be moved
from seekdir position. seekdir takes one of the following three seek direction constants - ios::beg,
ios::cur, ios::end.
Constant Meaning

ios::beg Offset specified from the beginning of the file

ios::cur Offset specified from the current position of the get pointer

ios::end Offset specified from the end of the file

Examples
inf.seekg(5, ios::beg);

Move the get pointer to the 5th byte (beginning of the file).
inf.seekg(20, ios::cur);

Moves the get pointer to the 20th byte from current position of the file in forward
direction.
inf.seekg(-20, ios::end);

The above example tells that the get pointer points to 20th byte in a file from end of file
in backward direction.

seekp()
There are two types.

• seekp(long);

• seekp(offset, seekdir);

seekp(long);
The seekp(long) function moves the put pointer to a specified location from the
beginning of a file.

Example
inf.seekp(20) ;
Tells that the put pointer to point 20th byte in a file from the beginning of
the file.

seekp(offset, seekdir)
The offset indicates the number of bytes the put pointer to be moved from seekdir
position. seekdir takes one of the three seek direction constants – ios::beg, ios::cur, ios::end.

Examples
1) inf.seekp(8, ios::beg);

Move the put pointer to the 8th byte (beginning of the file) for writing.
2) inf.seekp(20, ios::cur) ;
Move the put pointer to the 20th byte from current position of the file in
forward direction for writing.
3) inf.seekp(-20, ios::end) ;
The put pointer points to 20th byte in a file from end-of-file in backward
direction.

tellg() member function


It is a member function in ‘ifstream’ class. It returns the current position of
the get pointer.

Syntax
int position;

position = fileobjectname.tellg();

tellp() member function


It is a member function in ofstream class. This function returns the current
position of the put pointer.

Syntax
int position;
position = fileobjectname.tellp();

You might also like