fs lab manual final 2014 - pesit south campus lab manual_final_2014.pdffs lab manual (10isl67) ......

49
FS Lab Manual (10ISL67) ISE 1 PESIT- SOUTH CAMPUS 1Km before Electronic City, Hosur Road, Bangalore-560100. DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING VI SEMESTER LAB MANUAL SUBJECT: File Structures Lab SUBJECT CODE: 10ISL67 SESSION: Jan 2014 – May 2014

Upload: ngodang

Post on 24-Apr-2018

222 views

Category:

Documents


3 download

TRANSCRIPT

FS Lab Manual (10ISL67) ISE 1

PESIT- SOUTH CAMPUS

1Km before Electronic City, Hosur Road, Bangalore-560100.

DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

VI SEMESTER

LAB MANUAL

SUBJECT: File Structures Lab

SUBJECT CODE: 10ISL67

SESSION: Jan 2014 – May 2014

FS Lab Manual (10ISL67) ISE 2

FS LAB MANUAL

Design, develop, and implement the following programs

1. Write a C++ program to read series of names, one per line, from standard input and write

these names spelled in reverse order to the standard output using I/O redirection and pipes.

Repeat the exercise using an input file specified by the user instead of the standard input and

using an output file specified by the user instead of the standard output.

2. Write a C++ program to read and write student objects with fixed length records and the

fields delimited by “|”. Implement pack ( ), unpack ( ), modify ( ) and search ( ) methods.

3. Write a C++ program to read and write student objects with Variable - Length records

using any suitable record structure. Implement pack ( ), unpack ( ), modify ( ) and search ( )

methods.

4. Write a C++ program to write student objects with Variable -Length records using any

suitable record structure and to read from this file a student record using RRN.

5. Write a C++ program to implement simple index on primary key for a file of student

objects. Implement add ( ), search ( ), delete ( ) using the index.

6. Write a C++ program to implement index on secondary key, the name, for a file of student

objects. Implement add ( ), search ( ), delete ( ) using the secondary index.

7. Write a C++ program to read two lists of names and then match the names in the two lists

using Co-sequential Match based on a single loop. Output the names common to both the

lists.

8. Write a C++ program to read k Lists of names and merge them using k-way merge

algorithm with k = 8.

9. Write a C++ program to implement B-Tree for a given set of integers and its operations

insert ( ) and search ( ). Display the tree.

10. Write a C++ program to implement B+ tree for a given set of integers and its operations

insert ( ), and search ( ). Display the tree.

11. Write a C++ program to store and retrieve student data from file using hashing. Use any

collision resolution technique.

12. Write a C++ program to reclaim the free space resulting from the deletion of records

using linked lists.

FS Lab Manual (10ISL67) ISE 3

/*******************************************************************

********

Problem Statement –

1. Write a C++ program to read series of names, one per line, from standard input and write

these names spelled in reverse order to the standard output using I/O redirection and pipes.

Repeat the exercise using an input file specified by the user instead of the standard input and

using an output file specified by the user instead of the standard output.

********************************************************************

*******/

AIM: The aim of this program is to read some names from standard input device like

keyboard and reverse the names and display them on standard output device like monitor.

Repeat the same by reading the names from a file, reverse them and write the reversed names

onto an new file.

Concepts-

Keywords: I/O redirection, Pipes

I/O redirection: There are always three default files open, stdin (the keyboard), stdout

(the screen), and stderr (error messages output to the screen). These, and any other open

files, can be redirected. Redirection simply means capturing output from a file, command,

program, script, or even code block within a script and sending it as input to another file,

command, program or script.

Pipes: A pipe is nothing but a temporary storage place where the output of one command is

stored and then passed as the input for second command. Pipes are used to run more than two

commands ( multiple commands) from same command line.

Algorithms-

1. Enter your choice” 1. From standard I/O 2. From Files”

2. Case 1: [using standard I/O]

Enter the number of names to be read, Read N

2a. Read one name at a time

2b. Apply reverse( ) function on each name and display the reversed name on

standard O/P

Repeat 2a and 2b for N times

3. Case 2: [Using Files]

cout<<"Enter the input file name: ";

cin>>in_file;

fout.open(in_file);

FS Lab Manual (10ISL67) ISE 4

cout<<"Enter the number of names: ";

cin>>n;

cout<<"Enter the names:\n";

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

{

cin>>name;

fout<<name<<endl;

}

fout.close();

fin.open(in_file);

cout<<"\nEnter the output file name: ";

cin>>out_file;

fout.open(out_file);

cout<<"\nThe names in reverse are:\n";

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

{

fin>>name;

rev=reverse(name);

//cout<<rev<<endl;

fout<<rev<<endl;

}

Close the two files.

4. [Function reverse( )]

Void reverse(char a[])

{

int len=strlen(a);

for(int i=0,j=len-1;i<len/2;++i,--j)

swap(a[i],a[j]);

}

5. [Function swap( )]

swap(char &a, char &b)

{

char temp=a;

a=b;

b=temp;

}

/*******************************************************************

********

Output – 1.Std O/P 2.File 3.Exit

1

Enter the number of names: 3

Enter 3 names:

FS Lab Manual (10ISL67) ISE 5

MANISH

ALBERT

MICHAEL

The reversed names are:

HSINAM

TREBLA

LEAHCIM

Done!

1.Std O/P 2.File 3.Exit

2

Enter the input file name: in

Enter the number of names: 2

Enter the names:

kashyap

kavitha

Enter the output file name: out

The names in reverse are:

payhsak

ahtivak

*******

***********************************************************************/

/**************************************************************************

*******

Problem Statement –

2. Write a C++ program to read and write student objects with fixed-length records and the

fields delimited by “|”. Implement pack( ), unpack ( ), modify ( ) and search ( ) methods.

***************************************************************************

*******/

Aim: The aim of this problem is to create a text file to store student information using fixed

length record where fields of the record is delimited by ‘|’ and to implement the functions

search( ) and modify( ) on these records.

Concepts:

Keywords: Fixed length record, field, delimiter

Fixed length records: A data file that contains data records of equal and constant length. All

records in the file are the same size. Each field will have a predetermined and unchanging

size, set when the record layout is designed, and the sum of the field sizes will add up to the

record size. If the data stored in a given field contains fewer characters than the defined size,

the rest of the field will be filled with spaces, or some other special characters.

FS Lab Manual (10ISL67) ISE 6

Fields and delimiter: Fields are the building blocks of records. These are the sections of a

record where information is stored. A delimiter is a sequence of one or more characters used

to specify the boundary between, independent regions in plain text or other data streams(i.e.

between two fields of a record or between two records of a file).

class student

{

char name[25],usn[11],age[3],buf[LEN];

void pack();

void unpack();

public:

void add();

void display();

void search();

void modify();

};

Function pack( ) packs the fields data (eg. usn, name and age) of a record along with a

delimiter ‘|’ between the fields into a buffer. Since it’s a fixed length record, the remaining

spaces are packed with special character #.

Example: After pack, 123|Ames John|20#########

void student::pack()

{

strcpy(buf,usn);

strcat(buf,"|");

strcat(buf,name);

strcat(buf,"|");

strcat(buf,age);

for(int i=strlen(buf); i<LEN; i++) // LEN is the length of the record fixed

strcat(buf,"#");

}

Function unpack ( ) remove the delimiters between the data of a record and copy the fields

(data) into memory.

void student::unpack()

{

strcpy(usn,strtok(buf,"|"));

strcpy(name,strtok(NULL,"|"));

strcpy(age,strtok(NULL,"#"));

}

Example: After unpack, usn = 123, name = Ames John, age = 20

Function add( ) : This function adds one record to the student file

FS Lab Manual (10ISL67) ISE 7

void student::add( )

{

cout<<"Enter USN: ";

cin>>usn;

cout<<"Enter name: ";

cin>>name;

cout<<"Enter age: ";

cin>>age;

pack( );

ofstream fout;

fout.open("student",ios::app);

fout<<buf<<endl;

fout.close( );

cout<<"Student record added\n";

}

Function display( ): display all the records of the student file

void student::display( )

{

ifstream fin;

fin.open("student");

while(!fin.eof( ))

{

fin>>buf;

if(fin.fail( ))

break;

unpack( );

cout<<"\nUSN: "<<usn<<"\nName: "<<name<<"\nAge: "<<age<<endl;

}

fin.close();

}

Function search( ): This function searches for a record in the file based on a given usn using

sequential search.

void student::search( )

{

ifstream fin;

fin.open("student");

char key[4];

cout<<"Enter the key: ";

cin>>key;

while(!fin.eof( ))

FS Lab Manual (10ISL67) ISE 8

{

fin>>buf;

if(fin.fail( ))

break;

unpack( );

if(!strcmp(usn,key))

{

cout<<"\nStudent Found!"<<"\nUSN: "<<usn<<"\nName: "<<name<<"\nAge:

"<<age<<endl;

fin.close( );

return;

}

}

cout<<"\nStudent not found\n";

fin.close( );

}

Function modify( ): this function searches a record in the file based on the given usn, if

found then modify/change the data of that student otherwise display a message.

void student::modify( )

{

fstream f;

f.open("student",ios::in|ios::out);

char key[4];

cout<<"Enter the key: ";

cin>>key;

while(!f.eof( ))

{

f>>buf;

if(f.fail( ))

break;

unpack( );

if(!strcmp(usn,key))

{

cout<<"\nStudent found\n"<<"Enter new name: ";

cin>>name;

cout<<"Enter new age: ";

cin>>age;

pack( );

f.seekp((int)f.tellg( )-LEN,ios::beg);

f<<buf;

f.close( );

FS Lab Manual (10ISL67) ISE 9

return;

}

}

cout<<"\nStudent not found\n";

f.close( );

}

Algorithm:

1. Create a menu for selection of users choice

student s; //object s

do {

cout<<"\n1. Add\n2. Display\n3. Search\n4. Modify\n5.

Exit\n\nEnter choice: ";

cin>>ch;

switch(ch)

{

case 1:

s.add();

break;

case 2:

s.display();

break;

case 3:

s.search();

break;

case 4:

s.modify();

break;

case 5:

break;

default:

cout<<"Wrong choice!";

}

}

while(ch!=5);

/**************************************************************************

*******

Output – 1. Add

2. Display

3. Search

4. Modify

FS Lab Manual (10ISL67) ISE 10

5. Exit

Enter choice: 1

Enter USN: 42

Enter name: Abcdef

Enter age: 21

Student record added

1. Add

2. Display

3. Search

4. Modify

5. Exit

Enter choice: 2

42|Abcdef|21#################

50|abcde|20##################

1. Add

2. Display

3. Search

4. Modify

5. Exit

Enter choice: 4

Enter the key: 42

Student found

Enter new name: Kopparam

Enter new age: 20

*************************************************************************/

/**************************************************************************

*******

Problem Statement –

3. Write a C++ program to read and write student objects with Variable - Length records

using any suitable record structure. Implement pack(), unpack(), modify() and search()

methods.

***************************************************************************

*******/

Aim: The aim of this problem is to create a text file to store student information using

variable length record where fields of the record is delimited by ‘|’ and to implement the

functions search( ) and modify( ) on these records.

Concepts:

Keywords: Variable length record, field, delimiter

FS Lab Manual (10ISL67) ISE 11

Variable length records: A data file that contains data records of variable length. All

records in the file are of the different size. Each field will have a predetermined size, set

when the record layout is designed, and the sum of the field sizes will add up to the record

size. Each record will have different size depending on the number of characters entered.

class student

{

char name[25],usn[11],age[3],buf[50];

void pack();

void unpack();

public:

void add();

void display();

void search();

void modify();

};

Function pack( ) packs the fields data (eg. usn, name and age) of a record along with a

delimiter ‘|’ between the fields into a buffer.

Example: After pack 123|Ames John|20#125|Bethoven|21#

Where # is the separator between two record

OR, 123|Ames John|20

125|Bethoven|21

void student::pack()

{

strcpy(buf,usn);

strcat(buf,"|");

strcat(buf,name);

strcat(buf,"|");

strcat(buf,age);

}

Function unpack ( ) remove the delimiters between the data of a record and copy the fields

(data) into memory.

void student::unpack( )

{

strcpy(usn,strtok(buf,"|"));

strcpy(name,strtok(NULL,"|"));

strcpy(age,strtok(NULL,"\n")); //OR part of the above example in pack( )

}

FS Lab Manual (10ISL67) ISE 12

Example: After unpack usn = 123, name = Ames John, age = 20

Function add( ) : This function adds one record to the student file

1. Read the data (i.e. usn, name, age) of a student

2. Pack the data using pack( ) function

3. Open the file in append mode and write the packed data into it.

4. Close the file.

Function display( ): display all the records of the student file

1. Open the file in read mode

2. Repeat the following until reached end of the file

2a. read one record

2b. unpack the data using unpack( ) function

2c. display the data (i.e. usn, name, age) on screen

3. Close the file

Function search( ): This function searches for a record in the file based on a given usn using

sequential search.

1. Read the usn to be searched

2. Open the file in read mode

3. Repeat the following,

3a. read a record

3b. unpack the read record

3c. compare the usn field with the usn entered in step 1.

3d. if both the usn are same then display the record;

close the file and terminate.

3e. otherwise, repeat step 3.

4. Display “record not found”

5. Close the file.

Function modify( ): this function searches a record in the file based on the given usn, if found

then modify/change the data of that student otherwise display a message.

1. Read the usn to be searched

2. Open the file in read/write mode

fstream f;

f.open("student",ios::in|ios::out);

3. Repeat the following,

3a. read a record

3b. unpack the read record

3c. compare the usn field with the usn entered in step 1.

3d. if same, change the name and age;

pack the new data with the same usn;

write the packed data into the same position of the file;

FS Lab Manual (10ISL67) ISE 13

close the file and terminate.

3e. otherwise, repeat step 3.

4. Display “record not found”

5. Close the file.

Algorithm:

1. Create a menu for selection of users choice

student s; //Object s

do {

cout<<"\n1. Add\n2. Display\n3. Search\n4. Modify\n5.

Exit\n\nEnter choice: ";

cin>>ch;

switch(ch)

{

case 1:

s.add();

break;

case 2:

s.display();

break;

case 3:

s.search();

break;

case 4:

s.modify();

break;

case 5:

break;

default:

cout<<"Wrong choice!";

}

}

while(ch!=5);

/**************************************************************************

*

Output – 1. Add

2. Display

3. Search

4. Modify

5. Exit

Enter choice: 1

FS Lab Manual (10ISL67) ISE 14

Enter USN: 42

Enter name: Abcdef

Enter age: 21

Student record added

1. Add

2. Display

3. Search

4. Modify

5. Exit

Enter choice: 2

42|Abcdef|21

1. Add

2. Display

3. Search

4. Modify

5. Exit

Enter choice: 4

Enter the key: 42

Student found

Enter new name: Kopparam

Enter new age: 20

*************************************************************************/

/*******************************************************************

********

Problem Statement –

4. Write a C++ program to write student objects with Variable - Length fields using any

suitable record structure and to read from this file a student record using RRN.

********************************************************************

*******/

Aim: The aim of this problem is to create a text file to store student information using fixed

length record where fields of a record is delimited by ‘|’ and each of the records will be

addressed by its RRN. We need to implement a function to access a record using its RRN to

reduce the search time.

Concepts:

Keywords: RRN (relative record number)

Relative Record Number (RRN): It’s an integer that is used to represent a fixed length

record. RRN starts with 0 followed by 1,2,3,…. where RRN 0 represent 1st record, RRN 1

FS Lab Manual (10ISL67) ISE 15

represent 2nd

record and so on. If length of a record is N and RRN of that record is R then

address of that record is calculated as R * N.

#define LEN 48

class student

{

char name[25],usn[11],age[3],buf[LEN];

void pack();

void unpack();

public:

void write_file();

void read_file();

};

pack( ) and unpack( ) functions are same as program 2.

Function write_file( ): This function adds one record to the student file (similar to add( ) of

the previous problem)

void student::write_file( )

{

cout<<"Enter USN: ";

cin>>usn;

cout<<"Enter name: ";

cin>>name;

cout<<"Enter age: ";

cin>>age;

pack( );

fout.open("student",ios::app);

fout<<buf<<endl;

cout<<"Student record added\n";

fout.close( );

}

Function read_file( ): This function reads a RRN of a record and searches for the record

based on the RRN provided. If the record with the given RRN is found then it displays the

desired record.

void student::read_file( )

{

int rrn;

char ch;

cout<<"Enter the RRN: ";

cin>>rrn;

FS Lab Manual (10ISL67) ISE 16

fin.open("student");

fin.seekg(rrn*(LEN+1),ios::beg);

fin>>buf;

unpack();

cout<<"\nUSN: "<<usn<<"\nName: "<<name<<"\nAge: "<<age<<endl;

fin.close( );

}

Algorithm:

1. Create the user menu

student s;

do

{

cout<<"\n1. Add a record\n2. Display a record\n3.

Exit\n\nEnter choice: ";

cin>>ch;

switch(ch)

{

case 1:

s.write_file();

break;

case 2:

s.read_file();

break;

case 3:

break;

default:

cout<<"Wrong choice!";

}

}while(ch!=3);

/**************************************************************************

Output – 1. Add a record

2. Display a record

3. Exit

Enter choice: 1

Enter USN: 42

Enter name: Abcdef

Enter age: 21

Student record added

1. Add a record

2. Display a record

3. Exit

FS Lab Manual (10ISL67) ISE 17

Enter choice: 1

Enter USN: 46

Enter name: skc

Enter age: 20

Student record added

1. Add a record

2. Display a record

3. Exit

Enter choice: 2

Enter the RRN: 1

USN: 46

Name: skc

Age: 20

**************************************************************************/

/**************************************************************************

Problem Statement -

5. Write a C++ program to implement simple index on primary key for a file of student

objects. Implement add ( ), search ( ), delete ( ) using the index.

**************************************************************************/

Aim: To create a text file with fixed length records or variable length records, an index file

with key(USN) and record address where entire record can be found and to show how

indexing is performed

Concepts:

Key words:

Index table: a table containing key and its address

Primary index: unique key that represents a record in a file

key: an entry in index table which uniquely identifies the record.

Operations performed on index file

1. Create the original empty index and data files

2. Load the index file into memory before using it

3. Rewrite the index file after using it

4. Add data records to the data file

5. Delete records from the data file

6. Update the index file to reflect the changes in the data file

Functions used in the above program

FS Lab Manual (10ISL67) ISE 18

//creating the index file.

Student::Student ()

{

int i; n = 0;

fin.open ("index");

if (!fin.fail ())

{

for (i = 0; !fin.eof (); i++)

{

fin >> buf[i];

if (fin.fail ())

break;

}

n = i;

fin.close ();

}

fin.open ("student");

fout.open ("student", ios::app);

}

//Adding record to the data file and

void Student::Add ()

{

int i, j, pos;

char *temp, temp1[20];

cout << "Enter USN: ";

cin >> usn;

cout << "Enter name: ";

cin >> name;

cout << "Enter age: ";

cin >> age;

pack ();

pos = fout.tellp ();

fout << str << endl;

fout.flush ();

sprintf (buf[n], "%s|%d", usn, pos);

cout << "Student record added\n";

n++;

}

int Student::Find (char buf[ ][20], char *key, int n)

{

char *usn, temp[50];

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

{

strcpy (temp, buf[i]);

usn = strtok (temp, "|");

FS Lab Manual (10ISL67) ISE 19

if (strcmp (key, usn) == 0) return i;

}

return -1; //key not found

}

//Searching for a record

void Student::Search ()

{

char key[4], temp[20], *temp1;int index, RecAddr;

cout << "Enter the key: "; cin >> key;

if ((index = Find (buf, key, n)) == -1)

cout << "Record not found!\n";

else

{

cout << "Student found!\n";

strcpy (temp, buf[index]);

temp1 = strtok (temp, "|");

RecAddr = atoi (strtok (NULL, "\n"));

fin.seekg (RecAddr, ios::beg);

fin >> str;

unpack ();

cout << "Name: " << name;

cout << "\nUSN: " << usn;

cout << "\nAge: " << age << endl;

}

}

void student::del ()

{

char key[4];

int index;

cout << "Enter the key: ";

cin >> key;

if ((index = find (buf, key, n)) == -1)

cout << "Record not found!\n";

else

{

cout << "Record deleted\n";

buf[index][0] = '*';

}

}

//update the index file

Student::~Student ()

{

fout.close ();

fout.open ("index");

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

if (buf[i][0] != '*')

fout << buf[i] << endl;

FS Lab Manual (10ISL67) ISE 20

fout.close ();

fin.close ();

}

/*****************************************************************************

*** Problem Statement - 6. Write a C++ program to implement index on secondary key, the name, for a file of student

objects. Implement add ( ), search ( ), delete ( ) using the secondary index. ******************************************************************************

**/

Aim: To create a text file with fixed length records or variable length records, an index file

with primary key(USN),secondary key(name) and record address where entire student record

can be found and to show how indexing is performed

Concepts:

Key words:

Index: a table containing key and its address

Key: an entry in index table which uniquely identifies the record.

Secondary key: an entry in the index table (not unique, repetition of the key may occur)

which identifies the record.

Operations performed on index file

1. Create the original empty index and data files

2. Load the index file into memory before using it

3. Rewrite the index file after using it

4. Add data records to the data file

5. Delete records from the data file

6. Update the index file to reflect the changes in the data file

Functions used the above program

//creating the index file.

Student::Student ()

{

int i; n = 0;

fin.open ("index");

if (!fin.fail ())

{

for (i = 0; !fin.eof (); i++)

{

fin >> buf[i];

if (fin.fail ())

break;

FS Lab Manual (10ISL67) ISE 21

}

n = i;

fin.close ();

}

fin.open ("student");

fout.open ("student", ios::app);

}

//Adding record to the data file

void Student::Add ()

{

int i, j, pos;

char *temp, temp1[20];

cout << "Enter USN: ";

cin >> usn;

cout << "Enter name: ";

cin >> name;

cout << "Enter age: ";

cin >> age;

Pack ();

pos = fout.tellp ();

fout << str << endl;

fout.flush ();

sprintf (buf[n], "%s|%s|%d", name,usn,pos);//seconday index

cout << "Student record added\n";

n++;

}

int Student::Find (char buf[][20], char *key, int n)

{

char *name, temp[50];

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

{

strcpy (temp, buf[i]);

name = strtok (temp, "|");

if (strcmp (key, name) == 0) return i;

}

return -1; //key not found

}

//Searching for a record

void Student::Search ()

{

char key[4], temp[20], *tempusn,*tempname;

FS Lab Manual (10ISL67) ISE 22

int index, RecAddr;

cout << "Enter the key: "; cin >> key;

if ((index = Find (buf, key, n)) == -1)

cout << "Record not found!\n";

else

{

cout << "Student found!\n";

strcpy (temp, buf[index]);

tempusn = strtok (temp, "|");

tempname = strtok (NULL, "|");

RecAddr = atoi (strtok (NULL, "\n"));

fin.seekg (RecAddr, ios::beg); //move the file pointer to the data record in data file

fin >> str; // Read the record

Unpack ();

cout << "Name: " << name; /* display the individual fields */

cout << "\nUSN: " << usn;

cout << "\nAge: " << age << endl;

}

}

// delete function

void student::del ()

{

char key[4];

int index;

cout << "Enter the key: ";

cin >> key;

if ((index = find (buf, key, n)) == -1)

cout << "Record not found!\n";

else

{

cout << "Record deleted\n";

buf[index][0] = '*'; // mark the buffer with * for the deleted record

}

}

//updating the index table

Student::~Student ()

{

fout.close ();

fout.open ("index");

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

if (buf[i][0] != '*') //copy the records to the index file not marked with *

fout << buf[i] << endl;

fout.close ();

fin.close ();

}

FS Lab Manual (10ISL67) ISE 23

/**************************************************************************

Problem Statement –

7. Write a C++ program to read two lists of names and then match the names in the two lists

using Consequential Match based on a single loop. Output the names common to both the

lists.

***************************************************************************

****/

AIM: The aim of this program is to read two lists of names from standard input device like

keyboard and using consequential match based on a single loop compare both the list of

names and write the names to a file which are common to both the files and print them on

standard output device like monitor.

Concepts -

Keywords: Co-sequential match

Co-sequential Match: Coordinated processing of two or more sequential lists to produce a

single list.

We have at least two lists and they contain names in sorted order. From these two list we find

out the common names and write them to a new file.

It contains the match procedure as given below:

1. Initializing: we need to arrange the things in sorted order such a way that the

procedure gets going properly.

2. Getting and accessing the next list item: we need simple methods that support getting

the next list element and accessing it.

3. Synchronizing: we have to make sure that match will never be missed.

4. Handling end of file conditions: when to get to the end of either of Lists we need to

halt the program.

5. Recognizing errors: when an error occurs in the data, we need to detect it and take

some action.

Algorithms:

1. Start

2. Take two lists l1, l2 such that data in it is in sorted order.

3. Open these files f1.open("l1");

f2.open("l2");

Open the output file, fout.open(“out”)

4. Read from first file and store the data in buf1

f1>>buf1;

if(f1.fail()) // if read error occurs

FS Lab Manual (10ISL67) ISE 24

{

cout<<"List 1 empty\n";

return 0;

}

5. Read from second file, store the data in buf2 and check for read error.

6. Repeat the following until comparison of data between the two files are over

i. If values are equal then we will write these values on the new file, read the next data

from

both files

ii. Or if buf1 has greater value than buf2, read the next data from first file

iii. else read next data from second file.

while(1)

{

cmp_val=strcmp(buf1,buf2);

if(cmp_val == 0)

{

cout<<buf1<<endl;

fout<<buf1<<endl;

f1>>buf1;

if(f1.fail())

break;

f2>>buf2;

if(f2.fail())

break;

}

else if(cmp_val < 0)

{

f1>>buf1;

if(f1.fail())

break;

}

else

{

f2>>buf2;

if(f2.fail())

break;

}

}

FS Lab Manual (10ISL67) ISE 25

9.Stop

/**************************************************************************

******

Output -

//Displays on console abigith

kashyap

neha

nikita

Contents of l1 – [1st file]

abigith

deepa

kashyap

kfc

neha

nikita

Contents of l2 – [2nd

file]

abigith

kashyap

keerti

neha

nikita

upasana

Contents of out – [output file]

abigith

kashyap

neha

nikita

***************************************************************************

*****/

/**************************************************************************

******

Problem Statement –

8. Write a C++ program to read k Lists of names and merge them using k-way merge

algorithm with k = 8.

***************************************************************************

*****/

FS Lab Manual (10ISL67) ISE 26

Aim: The aim of this program is to read K lists of names from standard input in sorted order

in each list and merge K number of lists in to one sequentially ordered list using K-way

Merge Algorithm and print merged list on standard output device.

Concepts -

Keywords: K-way Merge Algorithm

K-way Merge Algorithm: It is to merge K input lists to create a single sequentially ordered

list. It can be viewed as a process of deciding which two input items has the minimum value,

outputting that item, then moving ahead in the list from which that item is taken. In this we

take all k lists in sorted order.

It requires calling a minimum index function to find the index of item with the

minimum collating sequence value and an inner loop that finds all lists that are using that

item. In this we find the minimum and testing to see that in which list the item occurs and

which files therefore need to be read.

It works nicely if k value is less than or equal to 8

Algorithm:

1. Start.

2. We create 8 files with names in sorted order in each file.

3. Assign variables for processing of 8 files where open_files=8 (number of files

currently being opened) and more_names is a variable that checks whether all the

names of the file has been read or not. Ex., if more_names[i] = 1, some names of the

ith file has not been processed yet and if more_names[i] = 0, otherwise.

int open_files=8;

int more_names[8]={1,1,1,1,1,1,1,1};

4. It will display the details of all the files and will open all of them one by one and will

read the first data of all the files one by one.

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

{

sprintf(file_name,"file%d",i);

fin[i].open(file_name);

fin[i]>>buf[i];

}

FS Lab Manual (10ISL67) ISE 27

5. When opening the files we have to find the minimum value among first data of all the

files

while(open_files) //repeat the following until all the files are get closed

{

min=find_min(buf,more_names); //find the minimum if(strcmp(buf[min],prev_name)) //if two names are same remove duplicate in output file { strcpy(prev_name,buf[min]); fout<<buf[min]<<endl; // write the minimum in the output file cout<<buf[min]<<endl; fin[min]>>buf[min]; //read the next data from the file where minimum data was

present if(fin[min].fail()) // reach end of a file { more_names[min]=0; open_files--; } } else // no duplicate entries { fin[min]>>buf[min]; if(fin[min].fail()) { more_names[min]=0; open_files--; } }

In this code we will calculate minimum of two values each from the lists. In this we assume

first data of first list as min and will compare it with the first data of rest of all the lists and if

any other value is lesser than the min value then min value will be the other one.

int find_min(char buf[][25],int more_names[])

{

int min;

for(min=0;min<8;min++)

if(more_names[min])

break;

for(int i=min+1;i<8;i++)

if(strcmp(buf[min],buf[i]) > 0 && more_names[i])

min=i;

return min;

}

/**************************************************************************

******

Output -

FS Lab Manual (10ISL67) ISE 28

kashyap

keerti

kfc

kp

neha

niki

nikita

nivedita

Contents of file0 -

kfc

niki

nivedita

Contents of file1 - kashyap

kfc

kp

Contents of file2 -

kashyap

neha

nikita

Contents of file3 - keerti

kfc

niki

Contents of file4 -

kfc

niki

nivedita

Contents of file5 - kashyap

kfc

kp

Contents of file6 -

kashyap

neha

nikita

Contents of file7 - keerti

kfc

niki

FS Lab Manual (10ISL67) ISE 29

********************************************************************************/

/*****************************************************************************

***

Problem Statement -

12. Write a C++ program to reclaim the free space resulting from the deletion of records using

linked lists.

******************************************************************************

**/

Aim: The aim of this problem is to reuse the free spaces on disk that results from deletion of

a record from a file.

Concepts:

Keywords: reclaim of free space

Reclaim of free space: whenever a record is deleted from a file the space is not actually

cleared, data is still present at that location but is not accessible, as after deleting a record the

location is marked with a special character, usually ‘*’. The address of the ‘*’ marked

location is added to a list which maintains the information of all free locations on a disk. This

list is called available list which is maintained as a linked list. Whenever memory has to be

allocated to a record, it’s done from the available list.

class student

{

char name[25],usn[11],age[4],str[LEN];

char buf[100][LEN];

int n,avail_list;

fstream file;

void pack();

void unpack();

public:

student();

void add();

void del();

};

//Constructor to count the number of records in the file and initialize avail_list, where

avail_list is the pointer to the linked list

FS Lab Manual (10ISL67) ISE 30

student::student()

{

int i;

file.open("student",ios::in);

for(i=0;;i++)

{

file>>buf[i];

if(file.fail())

break;

if(i==0)

avail_list=atoi(buf[i]);

}

if(i==0)

{

n=i+1;

avail_list=-1;

}

else

n=i;

file.close();

}

Function pack( ) and unpack( ) are same with program 2.

Function add( ): adds a record to the end of the file if none of the records are deleted yet or

adds a new record in the place from where last deletion is done. We are maintaining a

stack(linked list) where the location of all the deleted items are added.

1. Read the data from keyboard and pack them using pack( );

2. Check if avail_list = -1, append the record to the file

3. Else add to the place of the last deleted record

4.

{

int temp=atoi(&(buf[avail_list][1]));

strcpy(buf[avail_list],str);

avail_list=temp;

n++;

}

5. //write the buffer to the file

int i;

sprintf(buf[0],"%d",avail_list);

file.open("student",ios::out|ios::trunc);

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

FS Lab Manual (10ISL67) ISE 31

file<<buf[i]<<endl;

file.close();

Function del( ): deletes a record from the file and add it to the stack (linked list).

1. Enter the usn to be deleted

2. for(i=1;i<n;i++)

{

char temp_buf[LEN],*usn_ptr;

strcpy(temp_buf,buf[i]);

usn_ptr=strtok(temp_buf,"|");

if(!strcmp(key,usn_ptr))

{

int temp=avail_list;

avail_list=i;

sprintf(buf[i],"*%d",temp);

cout<<"Student Record Deleted\n";

//copy the buffer to the file

sprintf(buf[0],"%d",avail_list);

file.open("student",ios::out|ios::trunc);

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

file<<buf[i]<<endl;

file.close();

return;

}

}

cout<<"Student not found\n"; // if the usn is not present in the file

Function main( ):

Create an object and menu to enter the choice of an user like other programs.

do

{

cout<<"\n1. Add\n2.Delete\n4. Exit\n\nEnter choice: ";

cin>>ch;

switch(ch)

{

case 1:

s.add();

break;

case 2:

s.del();

break;

FS Lab Manual (10ISL67) ISE 32

case 3:

break;

default:

cout<<"Wrong choice!";

}

}while(ch!=3);

/***********************************************************************

*********

Problem Statement -

11. Write a C++ program to store and retrieve student data from

file using hashing. Use any collision resolution technique. ************************************************************************

********/

Aim: aim is to create a file using hashing technique and retrieve a

data using the same concept. We are supposed to handle collision

by using any of the collision resolution techniques.

Concepts:

Keywords:

Hashing- is a technique which needs to retrieve a data from a database in constant time.

There are various methods to create database (hash table) in constant time using different

hash functions.

Collision: if for two different data, hash function gives the same hash address then both

the data collide.

Collision resolution techniques: there are various methods available using which collision

can be resolved. (refer to your text book).

#define LEN 40

#define N 5

class student

{

char name[25],usn[11],age[4],str[LEN];

int fd;

FS Lab Manual (10ISL67) ISE 33

unsigned int hash(char*);

void pack();

void unpack();

public:

student();

~student();

void add();

void search();

};

//Constructor

student::student()

{

if( ( fd=open("./student",O_RDWR) ) == -1)

{

char buf[(LEN+1)*N];

int i;

for(i=0;i<(LEN+1)*N;i++) // initialize the buffer or hash

table

buf[i]='/';

fd=open("./student",O_RDWR|O_CREAT|O_EXCL,0666);

write(fd,buf,(LEN+1)*N); //open a file and write the buffer

}

}

void student::pack()

{

strcpy(str,usn);

strcat(str,"|");

strcat(str,name);

strcat(str,"|");

strcat(str,age);

for(int i=strlen(str);i<LEN-1;i++)

strcat(str,"#");

}

FS Lab Manual (10ISL67) ISE 34

void student::unpack()

{

strcpy(usn,strtok(str,"|"));

strcpy(name,strtok(NULL,"|"));

strcpy(age,strtok(NULL,"#"));

}

unsigned int student::hash(char *str)

{

//djb2 algorithm to calculate the hash address

unsigned int hash = 0;

int c;

while (c = *str++)

hash=hash*33+c;

return hash % N;

}

// add one record to hash table using hash function mentioned

above

void student::add()

{

int home_address,i=0;

char test;

char test_buf[2];

cout<<"Enter USN: ";

cin>>usn;

cout<<"Enter name: ";

cin>>name;

cout<<"Enter age: ";

cin>>age;

pack( );

home_address=hash(name);

while(1)

{

if(i==N)

FS Lab Manual (10ISL67) ISE 35

{

cout<<"Overflow!\n"; // hash table doesn’t have space

return;

}

lseek(fd,(LEN+1)*home_address,SEEK_SET);

read(fd,&test,sizeof(test));

if(test=='/') //hash address is free or no collision

break;

home_address=(home_address+1)%N;

i++;

}

lseek(fd,(LEN+1)*home_address,SEEK_SET);

write(fd,str,LEN);

write(fd,"\n",1);

}

//function to search for a record using hash function

void student::search()

{

char key[25];

int home_address,i=0;

cout<<"Enter key: ";

cin>>key;

home_address=hash(key);

do

{

lseek(fd,(LEN+1)*home_address,SEEK_SET);

read(fd,str,LEN);

unpack();

home_address=(home_address+1)%N;

i++;

}while(strcmp(name,key) && i<N);

FS Lab Manual (10ISL67) ISE 36

if(strcmp(name,key))

cout<<"Not found!\n";

else

{

cout<<"Student found\n";

cout<<"Name = "<<name;

cout<<"\nUSN = "<<usn;

cout<<"\nAge = "<<age<<endl;

}

}

student::~student()

{

close(fd);

} int main()

{

int ch;

student s;

do

{

cout<<"\n1. Add\n2. Search\n3. Exit\n\nEnter choice: ";

cin>>ch;

switch(ch)

{

case 1:

s.add();

break;

case 2:

s.search();

break;

case 3:

break;

default:

cout<<"Wrong choice!";

}

}while(ch!=3);

}

/***********************************************************************

FS Lab Manual (10ISL67) ISE 37

*********

/***********************************************************************

*********

Problem Statement -

9. Write a C++ program to implement B-Tree for a given set of integers and its operations

insert ( ) and search ( ). Display the tree.

************************************************************************

********/

Aim: aim of this program is to implement B-tree on a set of integer numbers and perform

some basic operations like insert an integer, search for a given integer and display the

tree.

Concepts:

Keywords:

B-tree-The B-tree is the classic disk-based data structure for indexing records based on

an ordered key set. It’s a height balanced tree where all the leaves are at the same level.

One node can hold multiple keys where keys are sorted in increasing order and a node can

have multiple children nodes. Root node should have at least 2 keys. (Refer text book)

#define MAX 4

#define MIN 2

struct btnode

{

int count;

int value[MAX+1];

btnode *child[MAX+1];

};

class btree

{

private:

btnode *root;

public:

btree();

void insert(int);

int setval(int,btnode*,int*,btnode**);

btnode* search(int,btnode*,int*);

int searchnode(int,btnode*,int*);

FS Lab Manual (10ISL67) ISE 38

void iskeypresent(int);

void fillnode(int,btnode*,btnode*,int);

void split(int,btnode*,btnode*,int,int*,btnode**);

void clear(btnode*,int);

void copysucc(btnode*,int);

void merge(int);

void show();

void display(btnode*);

void deltree(btnode*);

~btree();

};

btree::btree()

{

root=NULL ;

}

void btree::iskeypresent(int val)

{

int i;

if(searchnode(val,root,&i))

cout<<"Key found!"<<endl;

else

cout<<"Key Not found\n"<<endl;

}

void btree :: insert ( int val )

{

int i ;

btnode *c, *n ;

int flag ;

flag = setval ( val, root, &i, &c) ;

if ( flag )

{

n = new btnode ;

n -> count = 1 ;

n -> value[1] = i ;

n -> child[0] = root ;

n -> child[1] = c ;

root = n ;

}

}

int btree :: setval ( int val, btnode *n, int *p, btnode **c)

{

int k ;

if ( n == NULL )

FS Lab Manual (10ISL67) ISE 39

{

*p = val ;

*c = NULL ;

return 1 ;

}

else

{

if ( searchnode ( val, n, &k) )

{

cout << endl << "Key value already exists." << endl ;

return 0 ;

}

if ( setval ( val, n -> child[k], p, c ) )

{

if ( n -> count < MAX )

{

fillnode ( *p, *c, n, k ) ;

return 0;

}

else

{

split ( *p, *c, n, k, p, c ) ;

return 1;

}

}

return 0;

}

}

btnode * btree :: search ( int val, btnode *root, int *pos )

{

if ( root == NULL )

return NULL ;

else

if ( searchnode ( val, root, pos ) )

return root ;

else

return search ( val, root -> child[*pos], pos ) ;

}

int btree :: searchnode ( int val, btnode *n, int *pos )

{

if ( val < n -> value[1] )

{

*pos = 0 ;

return 0;

FS Lab Manual (10ISL67) ISE 40

}

else

{

*pos = n -> count ;

while ( ( val < n -> value[*pos] ) && *pos > 1 )

( *pos )-- ;

if ( val == n -> value[*pos] )

return 1 ;

else

return 0 ;

}

}

void btree::fillnode ( int val, btnode *c, btnode *n, int k )

{

int i ;

for ( i = n -> count ; i > k ; i--)

{

n -> value[i + 1] = n -> value[i] ;

n -> child[i + 1] = n -> child[i] ;

}

n -> value[k + 1] = val ;

n -> child[k + 1] = c ;

n -> count++ ;

}

void btree :: split ( int val, btnode *c, btnode *n, int k, int *y, btnode **newnode )

{

int i, mid ;

if ( k <= MIN )

mid = MIN ;

else

mid = MIN + 1 ;

*newnode = new btnode ;

for ( i = mid + 1 ; i <= MAX ; i++ )

{

( *newnode ) -> value[i - mid] = n -> value[i] ;

( *newnode ) -> child[i - mid] = n -> child[i] ;

}

( *newnode ) -> count = MAX - mid ;

n -> count = mid ;

if ( k <= MIN )

fillnode ( val, c, n, k ) ;

else

fillnode ( val, c, *newnode, k - mid ) ;

*y = n -> value[n -> count] ;

FS Lab Manual (10ISL67) ISE 41

( *newnode ) -> child[0] = n -> child[n -> count] ;

n -> count-- ;

}

void btree :: clear ( btnode *root, int k )

{

int i ;

for ( i = k + 1 ; i <= root -> count ; i++ )

{

root -> value[i - 1] = root -> value[i] ;

root -> child[i - 1] = root -> child[i] ;

}

root -> count-- ;

}

// copies the successor of the value that is to be deleted

void btree::copysucc ( btnode *root, int i )

{

btnode *temp = root -> child[i] ;

while ( temp -> child[0] )

temp = temp -> child[0] ;

root -> value[i] = temp -> value[1] ;

}

// merges two nodes

void btree :: merge ( int k )

{

btnode *temp1, *temp2 ;

temp1 = root -> child[k] ;

temp2 = root -> child[k - 1] ;

temp2 -> count++ ;

temp2 -> value[temp2 -> count] = root -> value[k] ;

temp2 -> child[temp2 -> count] = root -> child[0] ;

for ( int i = 1 ; i <= temp1 -> count ; i++ )

{

temp2 -> count++ ;

temp2 -> value[temp2 -> count] = temp1 -> value[i] ;

temp2 -> child[temp2 -> count] = temp1 -> child[i] ;

}

for (int i = k ; i < root -> count ; i++ )

{

root -> value[i] = root -> value[i + 1] ;

root -> child[i] = root -> child[i + 1] ;

}

root -> count-- ;

delete temp1 ;

}

FS Lab Manual (10ISL67) ISE 42

// calls display( )

void btree :: show( )

{

display ( root ) ;

}

// displays the B-tree

void btree :: display ( btnode *root )

{

int i;

if ( root != NULL )

{

for (i = 0 ; i < root -> count ; i++ )

{

display ( root -> child[i] ) ;

cout<<root->value[i+1]<<"\t";

}

display ( root -> child[i] ) ;

}

}

// deallocates memory

void btree::deltree ( btnode *root )

{

int i;

if ( root != NULL )

{

for (i = 0 ; i < root -> count ; i++ )

{

deltree ( root -> child[i] ) ;

delete ( root -> child[i] ) ;

}

deltree ( root -> child[i] ) ;

delete ( root -> child[i] ) ;

}

}

btree::~btree()

{

deltree(root);

}

int main()

{

btree b ;

int num;

int ch;

FS Lab Manual (10ISL67) ISE 43

do

{

cout<<"\n1. Insert\n2. Search\n3. Display\n4. Exit\n\nEnter your choice: ";

cin>>ch;

switch(ch)

{

case 1:

cout<<"\nEnter the value: ";

cin>>num;

b.insert(num);

break;

case 2:

cout<<"\nEnter the key: ";

cin>>num;

b.iskeypresent(num);

break;

case 3:

b.show();

break;

case 4:

break;

default:

cout<<"lnvalid Option!\n";

}

}while(ch!=4);

}

/***********************************************************************

*********

Problem Statement -

10. Write a C++ program to implement B+ tree for a given set of integers and its

operations insert ( ), and search ( ). Display the tree.

************************************************************************

********/

Aim: aim is to implement B+ tree on a set of integers and to perform the operations like

insert a number, search for a number and the tree.

Concepts:

Keywords:

FS Lab Manual (10ISL67) ISE 44

B+ tree- It is a variant of the original B-tree in which all records are stored in the leaves and

all leaves are linked sequentially. The B+ tree is used as a (dynamic) indexing method in

relational database management systems. B+ tree considers all the keys in nodes except the

leaves as dummies. All keys are duplicated in the leaves. This has the advantage that is all the

leaves are linked together sequentially; the entire tree may be scanned without visiting the

higher nodes at all. (Refer text book).

#define MAX 4

class Node

{

int info[MAX + 1];

Node* link[MAX + 1];

Node *parent;

Node *rlink;

int count;

Node();

void insert(int key, Node *p);

int search(int key);

void display();

int min()

{

return info[0];

}

void split(Node *n);

void updateParent();

friend class BPtree;

};

Node::Node()

{

for(int i = 0; i < MAX + 1; i++)

{

info[i] = -1;

link[i] = NULL;

}

parent = NULL;

rlink = NULL;

count = 0;

}

FS Lab Manual (10ISL67) ISE 45

void Node::insert(int key, Node *p = 0)

{

int i;

for(i = count - 1; i >= 0 && key < info[i]; i--)

{

info[i+ 1] = info[i];

link[i + 1] = link[i];

}

info[i + 1] = key;

link[i + 1] = p;

count++; //everytime you insert

}

int Node::search(int key)

{

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

if(info[i] == key)

return 1;

return 0;

}

void Node::display()

{

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

cout << info[i] << " ";

cout << endl; //don't forget this

}

void Node::split(Node *n)

{

n->info[0] = info[3]; n->link[0] = link[3];

n->info[1] = info[4]; n->link[1] = link[4];

count = 3;

n->count = 2;

if(n->link[0])

n->link[0]->parent = n;

if(n->link[1])

n->link[1]->parent = n;

n->parent = parent;

rlink = n;

}

void Node::updateParent()

{

FS Lab Manual (10ISL67) ISE 46

int i;

if(parent == NULL)

return;

for(i = 0; i < parent->count; i++)

if(parent->link[i] == this)

break;

parent->info[i] = min();

parent->updateParent(); //update parents recursively

}

class BPtree

{

Node *root;

public:

BPtree()

{

root = NULL;

}

Node* getLeaf(int key);

Node* getRoot()

{

return root;

}

void insert(int key);

void search(int key);

void display(Node *p, int level);

void free(Node *r);

~BPtree()

{

free(root);

}

};

Node* BPtree::getLeaf(int key)

{

int i;

Node *cur = root, *prev = NULL;

while(cur != NULL)

{

for(i = cur->count - 1; cur->info[i] > key && i >= 0; i--);

if(i == -1)

i++;

prev = cur;

cur = cur->link[i];

FS Lab Manual (10ISL67) ISE 47

}

return prev;

}

void BPtree::insert(int key)

{

if(root == NULL)

{

root = new Node;

root->insert(key);

return;

}

Node *thisNode, *newNode;

thisNode = getLeaf(key);

thisNode->insert(key);

thisNode->updateParent();

while(thisNode->count > MAX)

{ //overflow!!!

newNode = new Node;

thisNode->split(newNode);

if(thisNode == root)

{

root = new Node;

root->info[0] = thisNode->min();

root->link[0] = thisNode;

root->info[1] = newNode->min();

root->link[1] = newNode;

thisNode->parent = newNode->parent = root;

thisNode->rlink = newNode;

root->count = 2;

return;

}

thisNode->updateParent();

newNode->parent->insert(newNode->min(), newNode);

newNode->parent->updateParent();

thisNode = thisNode->parent; //iterate and check for overflow

}

}

void BPtree::search(int key)

{

if(root == NULL)

{

cout << "Empty tree\n";

FS Lab Manual (10ISL67) ISE 48

return;

}

Node *thisNode = getLeaf(key);

if(thisNode->search(key))

cout << "Found\n";

else

cout << "Not found\n";

}

void BPtree::display(Node *p, int level = 0)

{

int i;

if(p == NULL)

return;

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

cout << "\t";

p->display();

for(i = 0; i < p->count; i++)

display(p->link[i], level + 1);

}

void BPtree::free(Node *r)

{

if(r == NULL)

return;

for(int i = 0; i < MAX + 1; i++)

free(r->link[i]);

delete r;

r = NULL;

}

int main()

{

int choice, key;

BPtree b;

do

{

cout<<"1. Insert\n2. Search\n3. Display\n4. Exit\n\nEnter choice: ";

cin>>choice;

switch(choice)

{

case 1:

cout << "Enter the key to insert: ";

cin >> key;

FS Lab Manual (10ISL67) ISE 49

b.insert(key);

break;

case 2:

cout << "Enter the key to search: ";

cin >> key;

b.search(key);

break;

case 3:

b.display(b.getRoot());

break;

case 4:

break;

default:

cout << "Invalid choice\n";

}

}while(choice!=4);

}