CP Unit-V - RIT CSE (2)
CP Unit-V - RIT CSE (2)
CP Unit-V - RIT CSE (2)
UNIT-V
STRUCTURES
Structure is a constructed data type for packing data of different types. It is a convenient tool for
handling a group of logically related data items.
Advantages:
1. Structures enable the user to group together a collection of different data items of
different data types using a single name.
2. Structures help to organize complex data in a more meaningful way.
Example:
A structure can be used to represent a student‟s details such as student_name, rollno, marks etc
as follows
Struct student
{
char stud_name[20];
char stud_rollno[10];
float stud_mark1;
float stud_mark2;
float stud_mark3;
};
A structure definition creates a format that may be used to declare structure variables.
General format for structure definition is as follows:
In the above example book_bank is a tag-name that is optional one. If you give the tagname then
later in the program you can declare the variables using the given tag-name otherwise it is not
possible. The title, author, pages and price are members of the structure. While defining the
structure memory is not allocated for its members. Only during the declaration the memory is
allocated for the members. Thus the structure definition creates a template to represent a group of
logically related information. In the structure definition we should follow the rules stated below
1. The template is terminated with semicolon.
2.While the entire declaration is considered as a statement, each member is declared
independently for its name and type in a separate statement inside the template.
3. The tag name such as book_bank can be used to declare structure variables of its type
later in the program.
Example:
/*Program to illustrate the dot operator*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
}student1;
void main()
{
printf(“Enter student details\n”);
printf(“\nStudent Name : “);
scanf(“%s”,student1.stud_name);
printf(“\nRoll no : “);
scanf(“%s”,student1.stud_rollno);
printf(“\nMark1 : “);
scanf(“%f”,&student.mark1);
printf(“\nMark2 : “);
scanf(“%f”,&student.mark2);
printf(“\nMark3 : “);
scanf(“%f”,&student.mark3);
student1.tot = student1.mark1 + student1.mark2 + student1.mark3;
printf(“The student details are as follows….\n”);
printf(“Student name : %s\n”,student1.stud_name);
printf(“Roll no : %s\n”,student1.stud_rollno);
printf(“Marks : %f %f %f\n”,student1.mark1,student1.mark2,student1.mark3);
printf(“Total : %f\n”,student1.tot);
}
Comparison of structures
Two variables of same structure type can be compared in the same way as ordinary variables. If
book1 and book2 are of same type then it is possible to compare two variables as book1==
book2. Similarly we can assign book2 to book1 as book1=book2.etc.
C permits the use of arrays as structure members. In the previous example we have declared
three variables mark1, mark2, mark3. We can eliminate this by using an array to hold the 3
marks. Thus the declaration will be as like as follows.
struct student
{
char stud_name[25];
char stud_rollno[10];
float marks[3];
}s[3];
Thus in the above example student contains 3 elements - stud_name, stud_rollno, and an array of
3 marks. The marks can be accessed as stu[2].marks[1]. Thus it refers to the mark obtained in the
first subject by the second student.
Example:
/*Arrays within structures*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
CSE, RIT Page 6
float marks[3],tot;
};
void main()
{
static struct student s[3];
int I,j;
for(I=0;I<3;I++)
{
printf(“Enter student %d details\n”,i);
printf(“\nStudent Name : “);
scanf(“%s”,s[I].stud_name);
printf(“\nRoll no : “);
scanf(“%s”,s[I].stud_rollno);
s[I].tot=0;
for(j=0;j<3;j++)
{
printf(“\nMark%d : “,j);
scanf(“%f”,&s[I].marks[j]);
s[I].tot = s[I].marks[j];
}}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
for(j=0;j<3;j++)
{
printf(“Mark%d : %f \n”,j,s[I].marks[j]);
}
printf(“Total : %f\n”,s[I].tot); }}
Structures within the structure means nesting of structures. Nesting of structures is permitted in
„C‟. Let us consider the following structure definition to store the information about the student.
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3;
float tot;
};
The above structure defines student name, rollno, and the marks of the student. We can group the
marks into one sub structure as follows:
struct student
{
CSE, RIT Page 7
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1;
float mark2;
float mark3;
}m;
float tot;
}s[3];
A self-referential structure is used to create data structures like linked lists, stacks, etc.
Following is an example of this kind of structure:
struct struct_name
{
datatype datatype_name;
struct_name * pointer_name;
};
UNIONS
Unions are the concept derived from structure. So the definition of union is same as structure
except with the keyword union. The main difference between the structure and the union is in the
memory allocation only. In structure the memory is allocated for all the members included
within the structure and all can be accessed simultaneously. In union the memory is allocated
for the longest member in the union so that all the members in the union can share the
allocated memory one at a time.
Example:
union product
{
int quantity;
float price;
char code;
} p1;
In the above the memory is allocated based on the longest data type float. Thus 4 bytes will be
allocated and all members in the union share that memory.
Example:
/unions example*/
void main()
{
union samp
{
EXAMPLE-2
#include <stdio.h>
union test {
int x, y;
};
void main()
CSE, RIT Page 11
{
// A union variable t
union test t;
t.x = 2; // t.y also gets value 2
printf("After making x = 2:\n x = %d, y = %d\n\n",t.x, t.y);
OUTPUT:
After making x = 2:
x = 2, y = 2
After making y = 10:
x = 10, y = 10
4. The address of each member will be in 4. The address is same for all the members of a
ascending order This indicates that memory for union. This indicates that every member begins
each member will start at different offset at the same offset value.
values.
5 Altering the value of a member will not 5. Altering the value of any of the member will
affect other members of the structure. alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.
7. Several members of a structure can initialize 7. Only the first member of a union can be
at once. initialized.
We have been using integer field of size 16 bits to store data. There are occasions where
data items require much less than 16 bits space. In such cases, we waste memory space.
A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length. A word
can therefore be divided into a number of bit fields. The name and size of bit fields are defined
using a structure. The general form of bit field is:
Struct tag-name
{
Data-type name1: bit-length;
Data-type name2: bit-length;
……
……
Data-type nameN: bit-length;
}
The data-type is either int or unsigned int or signed int and the bit-length is the number of bits
used for the specified name.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
0
#include <stdio.h>
// A simple representation of the date
struct date {
unsigned int d;
unsigned int m;
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2020 };
Date is 31/12/2020
Since we know that the value of d is always from 1 to 31, the value of m is from 1 to 12, we can
optimize the space using bit fields.
#include <stdio.h>
struct date {
unsigned int d : 5;
unsigned int m : 4;
unsigned int y;
};
void main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2020 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
OUTPUT:
Date is 31/12/2020
TYPEDEF
The C programming language provides a keyword called typedef, which you can use to
give a type a new name. You can use typedef to give a name to user defined data type as well.
For example you can use typedef with structure to define a new data type and then use that data
type to define structure variables directly as follows:
EXAMPLE:
/*typedef example */
#include <stdio.h>
void main()
{
struct date
{
int day;
int mm;
int yy;
};
typedef struct date d;
struct student
{
int rno;
char name[20];
d jod; /* usage of typedef */
}s;
printf("\nEnter roll no: ");
scanf("%d",&s.rno);
printf("\n Enter name: ");
scanf("%s",s.name);
printf("\n Enter date of joining dd mm yy: ");
scanf("%d%d%d", &s.jod.day,&s.jod.mm,&s.jod.yy);
printf("\nno is %d", s.rno);
printf("\nname is %s",s.name);
printf("\njoining date %d-%d-%d",s.jod.day,s.jod.mm,s.jod.yy);
getch();
}
Output:
Enter Roll no: 100
Enter name: sastry
FILE HANDLING IN C:
• When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using a few commands in C.
• You can easily move your data from one computer to another without any changes.
• When accessing files through C, the first necessity is to have a way to access the files.
For C File I/O you need to use a FILE pointer, which will let the program keep track of
the file being accessed. For Example:
FILE *fp;
Types of Files:
When dealing with files, there are two types of files you should know about: Text files, Binary
files
1. Text files
• Text files are the normal .txt files. You can easily create text files using any simple text
editors such as Notepad.
• When you open those files, you'll see all the contents within the file as plain text. You can
easily edit or delete the contents.
• They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.
2. Binary files
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form (0's and 1's).
• They can hold a higher amount of data, are not readable easily, and provides better security
than text files.
• File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed on a
file.
If we want to store data in a file in the secondary memory, we must specify certain things about
the file, to the operating system. They include:
1. Filename
2. Data structure
3. Purpose
FILE *fp;
fp=open(“filename”,”mode”);
The first statement declares the variable fp as a “pointer to the data type FILE. The second
statement opens the file named filename and assigns an identifier to the FILE type pointer fp.
This pointer which contains all the information about the file is subsequently used as a
communication link between the system and the program.
Closing a file:
A file must be closed as soon as all operations on it have been completed. This ensures
that all outstanding information associated with the file is flushed out from from the buffers and
all links to the file are broken.
fclose(file_pointer);
Example: (file1.c)
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen(“test.txt", "w"); /* file(test.txt) opening in write mode*/
fprintf(fp, "This is testing...\n");
fclose(fp;);
}
CSE, RIT Page 18
This will create a file test.txt in and will write This is testing in that file.
Output at file(test.txt):
Hello, This is testing...
Example:
Program to create a data file containing student records*/
#include<stdio.h>
main()
{
FILE *fp;
int stno;
char stname[10];
int m1,m2,m3,n,i;
fp=fopen("stu.dat","w");
printf("enter no of students: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nstno: ");
scanf("%d",&stno);
printf("stname: ");
scanf("%s",stname);
printf("m1 m2 m3: ");
scanf("%d%d%d",&m1,&m2,&m3);
fprintf(fp,"%d %s %d %d %d\n",stno,stname,m1,m2,m3);
}
fclose(fp);
getch();
}
Output:
enter no of students: 2
stno: 101
stname: xyz
m1 m2 m3: 90 80 95
101 xyz 90 80 95
stno: 102
stname: pqr
m1 m2 m3: 88 87 89
102 pqr 88 87 89
The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
NOTE: You can use fgetc() and fputc() just in the same way as that of getc() and putc() functions.
Thus the statement
c = getc(fp);
reads the next character from the file referenced by fp and the statement
putc(c,fp);
The getw and putw are integer-oriented functions. They are similar to the getc and putc
functions and are used to read and write integer values. These functions would be useful when
we deal with only integer data. The general form of getw and putw are:
putw(integer, fp);
getw(fp);
Example program:
/*usage of getw, putw functions....*/
#include<stdio.h>
#include<conio.h>
void main()
{
f1=fopen("DATA","r");
f2=fopen("EVEN","w");
f3=fopen("ODD","w");
while((number=getw(f1))!=EOF)
{
if(number%2==0)
{
putw(number,f2);
}
else
putw(number,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("EVEN","r");
f3=fopen("ODD","r");
The functions fprintf and fscanf perform I/O operations that are identical to the familiar
printf and fscanf functions, except of course that they work on files. The first argument of these
functions is a file pointer which specifies the file to be used. The general form of fprintf is
where fp is file pointer associated with a file that has been opened for writing.
The control strings contains output specifications for the items in the list. (%d,%f,%s,%u,%e,
etc)
The list may include variables, constants and strings.
Example program:
/*usage of fprintf,fscanf functions....*/
#include<stdio.h> #include<conio.h>
void main()
{
FILE *fp;
There is no need to read each record sequentially, if we want to access a particular record.C
supports these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
1.fseek() :
It is used to move the reading control to different positions using fseek function.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position.This is attached
with L because this is a long integer.
0 means pointer position is on beginning of the file,from this statement pointer position is
skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is
skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the current
position.
Example Program:
Write a program to read last „n‟ characters of the file using appropriate file functions.
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("file1.c", "r");
if(fp==NULL)
printf("file cannot be opened");
else
{
printf("Enter value of n to read last „n‟ characters");
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf("%c\t",ch);
}
}
fclose(fp);
getch();
}
int main()
char string[20];
fscanf(fp,"%s",string);
printf("%ld", ftell(fp));
return 0;
3. rewind():
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer
Example Program ( Assume the file “file.txt” contains the text “this is a simple text”
#include<stdio.h>
#include<conio.h>
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
getch();
}
Output:
1. write a C program to copy the contents of one file into another file.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20];
printf("Enter name of first file\n");
gets(file1);
printf("Enter name of second file\n");
gets(file2);