IP Unit 5

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Introduction to Programming (AR23) Unit-V

UNIT – V User Defined Data types, File Handling


STRUCTURES: A structure is a collection of variables of different data types that are stored
consequently in memory locations logically grouped together and referred under a single name. Structure
is a heterogeneous collection of data elements. Structure is a user-defined data type. User- defined data
type also called as derived data type why because we derived it from the primary/basic data types.
Significance of Structure: A simple variable can store one value at a time. An array can store a number
of variables of the same type. For example, marks obtained by a student in five subjects canbe stored in
an array marks[5]. Then marks[0], marks[1], etc..., will store student information like the marks obtained
in various five subjects. Suppose we want to store student information in array like name, address, htno,
marks obtained. We cannot store this information in an array because name, htno, address are of
character type and marks obtained is of integer type. So Arrays are used to store homogeneous data. To
store heterogeneous data elements in a single group, C provides a facility called structure.
Differences between array and structure: Arrays are used to store homogeneous data elements in
single group Structures are used to store heterogeneous data elements in a single group
Declaration of Structure using struct keyword
struct structure_name
{
data_type member_variable_1;
data_type member_variable_2;
……
data_type member_variable_N;
};
The variables declared inside the structure are known as members of the structure.

Note: The members of the structure may be any of the common data type,pointers, arrays or even the
other structures. Structure definition starts with the open brace({) and ends with closing brace(})
followed by a semicolon (;).

Declaring structure variable


Structures declaration:
As stated earlier, the compiler does not reserve memory any memory when structure is defined. To
store members of structures in memory, we have to define the structure variables. The structure
variables may be declared in the following ways:
1. In the structure declaration
2. Using the structure tag

In the structure declaration, the structure variable can be declared after the closing brace (}).
Following example shows this.
struct date
{
int day;
int month;
int year;
}dob, doj;
Here date is the structure tag, while dob and doj are variables type date.
Using the structure tag: The variables of structure may also be declared separately by using the
structure tag as shown below:
struct date
NS Raju Institute of Technology Page 1
Introduction to Programming (AR23) Unit-V
{
int day;
int month;
int year;
}dob, doj;

Structure Example Program 1:


#include<stdio.h>
#include <string.h>
struct student
{
int roll no;
char
name[30];
}s;
void main( )
{
s.roll_no = 1;
strcpy(s.name, “sai”);
printf(“Student Enrollment No. : %d\n”, s.roll_no);
printf(“Student Name : %s\n”, s.name);
}
Output: Student Enrollment No. : 1
Student Name : sai

Structure Example Program 2:


#include<stdio.h>
struct student
{
char name[30];
int htno;
char gender;
int marks;
};
void main()
{
struct student st={"SAI",999,'M',90,"hyd"};
printf("Student Name:%s\n",st.name);
printf("Roll No:%d\n",st.htno);
printf("Gender:%c\n",st.gender);
printf("Marks obtained:%d\n",st.marks);
}
Student Name: SAI
Roll No:999
Gender:M
Marks obtained:90

Nested Structure in C : One structure with in another structure is called Nested Structure.
For example, we may need to store the address of an entity employee in a structure. The attribute address
may also have the subparts as street number, city, state, and pin code. Hence, to store the address of the

NS Raju Institute of Technology Page 2


Introduction to Programming (AR23) Unit-V
employee, we need to store the address of the employee into a separate structure and nest the structure
address into the structure employee.

// Example Nested Structure program


#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};

struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information ...\n");
printf("name:%s\nCity:%s\nPincode:%d\nPhone:%s",emp.name,emp.add.city,emp.add.pi
n, emp.add.phone);
}
OUTPUT: Enter employee information? saivijayawada
123123
1234567890
Printing the employee information....
name: sai
City: Vijayawada
Pincode: 123123
Phone: 1234567890

Array of structures : An array of structures in C can be defined as the collection of multiple structures
variables where each variable contains information about different entities. The array of structures in C
are used to store information about multiple entities of different data types. The arrayof structures is also
known as the collection of structures.
EXAMPLE
#include<stdio.h>
#include<string.h>
struct student
{
int rollno;
char name[10];
};
void main()
{
int i;

NS Raju Institute of Technology Page 3


Introduction to Programming (AR23) Unit-V
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnterRollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
}
OUTPUT: Enter Records of 5 students
Enter Rollno:1
Enter Name:ravi
Enter Rollno:2
Enter Name:ram
Enter Rollno:3
Enter Name:satya
Enter Rollno:4
Enter Name:kiran
Enter Rollno:5
Enter Name: srija
Student Information List:
Rollno:1,
Name: ravi Rollno:2,
Name: ram Rollno:3,
Name: satya Rollno:4,
Name: kiran Rollno:5,
Name: srija

Union: A Union is a user defined data type like structure. The union groups logically related
variables into a single unit. In structure each member has its own memory location; whereas
the members of union has the same memory location. We can assign values to Only one member
at a time can be assigned with values.
When a union is declared, compiler allocates memory locations to hold largest data type member in
the union. So, union is used to save memory. Union is useful when it is not necessary to assign the
values to all the members of the union at a time.
Union can be declared as: The union keyword is used to define the union. Let's see the syntax to
define union in c.
union union_name
{
data_type member1;
data_type member2;
data_type memberN;
};
NS Raju Institute of Technology Page 4
Introduction to Programming (AR23) Unit-V
Example:
union employee
{
int id;
char name[50];
float salary;
};
Union example program:
#include <stdio.h>
#include <string.h>
union employee
{
int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
e1.id=1; strcpy(e1.name, "jai");//copying string into char array
printf( "employee 1 id : %d\n", e1.id); //printing first employee information
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output: employee 1 id : 6906195
employee 1 name : jai
Note: According to Union id gets garbage value because name has large memory size. So only name
will have actual value.

Union example 2:
#include<stdio.h>
union student
{
char name[15];
int age;
};
int main()
{
union student st;
printf("Enter student name:");
scanf("%s",st.name);
printf("Student Name: %s & Age= %d\n",st.name,st.age);
st.age=20;
printf("Student Name: %s, age= %d\n",st.name,st.age);
}
OUTPUT: Enter student name: Jai
Student Name: jai & Age= 20
Student Name: Jai, age= 20
NOTE: First time union member name has a value which is inputted through the keyboard. So name is
displayed. Next time we were assigned a values to age, union will lost the value in member name, so
NS Raju Institute of Technology Page 5
Introduction to Programming (AR23) Unit-V
this time only student’s age is displayed.

We can access only one member of union at a time. We can’t access all member values at the same time
in union. But, structure can access all member values at the same time. This is because, Union allocates
one common storage space for all its members. Whereas Structure allocates storage space for all its
members separately.

Difference between structure and union :


S.No. Structure Union
1. Stores heterogeneous data Stores heterogeneous data
Members are stored separately in
2. Members are stored in same memory location.
memory locations.
In structures all the members are avail- In union only one member is available at a
3.
able. time.
Occupies more memory when compared Occupies less memory when compared
4.
to union with structure.
Size of the structure is the total Size of the union is the size of the
5.
memoryspace required by its members largestdata type member in the union.
struct student union student
{ {
char name[15]; char name[15];
6.
int age; int age;
}; };

Fig: Storage in structure

Fig: Storage in union

Example program with memory allocation of structure and union:


struct Employee
{
int age;
float Salary;
};
union Person
{
int age;
float Salary;
};
void main()
{
struct Employee emp1;
union Person Person1;
NS Raju Institute of Technology Page 6
Introduction to Programming (AR23) Unit-V
printf(" The Size of Employee Structure = %d\n", sizeof (emp1) );
printf(" The Size of Person Union = %d\n", sizeof (Person1));
}
Output: The Size of Employee Structure = 8
The Size of Person Union = 4

C Typedef : The typedef is a keyword used in C programming to provide some meaningful names to
the already existing variable in the C program. It behaves similarly as we define the alias for the
commands. In short, we can say that this keyword is used to redefine the name of an already existing
variable.
Syntax of typedef:
typedef <existing_name> <alias_name>;

In the above syntax, 'existing_name' is the name of an already existing variable while 'alias name' is
another name given to the existing variable.
Example: typedef unsigned int unit;
/*In the above statements, we have declared the unit variable of type unsigned int by using a typedef
keyword.
Now, we can create the variables of type unsigned int by writing the following statement:*/ unit a, b;
//instead of writing: unsigned int a, b;

TYPEDEF EXAMPLE 1:
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10; j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
OUTPUT: Value of i is :10
Value of j is :20

TYPEDEF EXAMPLE 2:
#include <stdio.h>
int main()
{
typedef int rectangle; //creating new data type name rectangle using typedef
rectangle length, breadth, area; //declaring variables using new data type name rectangle
printf("\nEnter length and breath of the rectangle ");
scanf("%d %d ", &length, &breadth);
area = length * breadth;
printf("\nArea = %d ", area);
return 0;
}
OUTPUT: Enter length and breadth of the rectangle 5 2
Area=10

NS Raju Institute of Technology Page 7


Introduction to Programming (AR23) Unit-V
Enumerations (enum): The enum in C is also known as the enumerated type. It is a user-defined
data type that consists of integer values, and it provides meaningful names to these values.
An enum is a keyword; it is a user defined data type. All properties of integer are applied on Enu-
meration data type so size of the enumerator data type is2 byte. It works like the Integer. It is used for
creating a user defined data type of integer. Using enum we can create sequence of integer constant
value.
Syntax: enum tagname {value1, value2, value3,.};

In above syntax enum is a keyword. It is a user defined data type. tagname is our own variable. tagname
is any variable name. value1, value2, value3,. Are

Creating Set of Enum Values.


It is start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the
list. If constant one value is not initialized then by default sequence will be start from zero and next to
generated value should be previous constant value one.
Example:
enum week {sun, mon, tue, wed, thu, fri, sat};
enum week today;

In above code first line is creating user defined data type called week. week variable have 7 values which
are inside { } braces.
today variable is declared as week type which can be initialize any data or value among 7 (sun, mon,).

Enum example:
#include <stdio.h>
enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
int days;
printf("enter a day:");
scanf("%d",&days);
switch(days)
{
case sunday: printf("Today is sunday"); break;
case monday: printf("Today is monday"); break;
case tuesday: printf("Today is tuesday"); break;
case wednesday: printf("Today is wednesday"); break;
case thursday: printf("Today is thursday"); break;
case friday: printf("Today is friday"); break;
case saturday: printf("Today is saturday"); break;

NS Raju Institute of Technology Page 8


Introduction to Programming (AR23) Unit-V
}
return 0;
}
OUTPUT: enter a day: 5 Today is Thursday

Enum example 2(with variable declaration)


#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
void main()
{
enum weekdays w; // variable declaration of weekdays
type w=Monday; // assigning value of Monday to w.
printf("The value of w is %d",w);
}
Output: The value of w is 2

FILES IN C
File : A File is a collection of related data stored on the hard disk.
Advantages of Files:
1. When large volumes of data are to be handled by the program.
2. When the data need to be stored permanently without getting destroyed when the program is
terminated.
The operations that you can perform on a File in C are −
1. Creating a new file
2. Opening an existing file
3. Reading data from an existing file
4. Writing data to a file
5. Moving data to a specific location on the file
6. Closing the file
Defining and Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen() function is used to open a file.
The syntax of the fopen() is given below.
FILE *fp;
fp = fopen(“filename”, “mode”);
Example: fp = fopen(“hello.txt”, “w”);

We can use one of the following modes in the fopen() function.

Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode

NS Raju Institute of Technology Page 9


Introduction to Programming (AR23) Unit-V
Closing a File : To close a file, use the fclose( ) function.
Syntax: int fclose( FILE *fp );

Functions for file handling


There are many functions in the C library to open, read, write, search and close the file. A list of file
functions are given below:

S.No. Function Description


1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
sets the file pointer to the beginning of
11 rewind()
the file

a) getc() – This function is used to read characters from the file that has been opened for read operation.
Syntax : c = getc(filepointer);
This statement reads a character from the file pointed by file pointer and assigns to c.

b) putc() – The putc function is used to write a character to a file.


Syntax : putc(c, filepointer);
This statement writes a character stored in the character variable c to the filehose file pointer is
filepointer.

c) getw() – This function reads an integer from file.


Syntax: getw(filepointer);

d) putw() – This function writes an integer to a file.


Syntax: putw(integer, filepointer);
e) fprintf() – This function performs similar to printf function. Writes data to a file.
Syntax: fprintf(fp, “controlstring”, list);
here fp is the filepointer opened in write mode.
Controlstring contains output specifications for the variables in the list.
List is the name of the variables.

f) fscanf() – This function works similar to scanf function. Reads a set of data from a file.
Syntax: fscanf(fp, “controlstring”, list);
here fp is the filepointer opened in write mode.
Controlstring contains output specifications for the variables in the list.
List is the name of the variables.

g) fclose() – A file can be closed as soon as all operations on it have been accepted.
Syntax: fclose(filepointer);

NS Raju Institute of Technology Page 10


Introduction to Programming (AR23) Unit-V
/* Read a string into a text file using fputs() function */
void main()
{
FILE *fp;
char text[80];
int i;
fp=fopen("Sample.txt","w");
printf("\n Enter the text : ");
gets(text);
fputs(text,fp); //write a string into a file
if(fp!=NULL)
printf("\n The string copied into a text file ");
fclose(fp);
}

/* read and write the content of the file using fprintf() and fscanf() functions */
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
fptr = fopen("abc.txt", "w"); /* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %f\n", salary);
fclose(fptr);
}

/* program to copy the binary file from another file */


void main()
{
FILE *fp,*fp1;
char *s,*s1;
int ch;
printf("\n enter the source file : ");
gets(s);
printf("\n enter the destination file : ");
gets(s1);

NS Raju Institute of Technology Page 11


Introduction to Programming (AR23) Unit-V
fp=fopen(s,"rb");
fp1=fopen(s1,"wb");
ch=fgetc(fp);
while(!feof(fp))
{
fputc(ch,fp1);
ch=fgetc(fp);
}
fclose(fp);
fclose(fp1);
}

Random Access to files of records


For random access to files of record, the following functions are used.
1. fseek() - by using fseek(), one can set the position indicator anywhere in the file.
Syntax: int fseek(FILE *fp, long offset, int origin);

Here, fp – file pointer


offset – It denotes the number of bytes which are skipped backward or forward from the
position specified in the third argument. It is a long integer which can be positive or
negative
origin – It is the position relative to which the displacement takes place. It takes one of the
following three values.

Constant Value Position


SEEK_SET 0 Beginning of file
SEEK_CURRENT 1 Current position
SEEK_END 2 End of file

2. ftell() – This function returns the current position of the file position pointer. The value is counted
from the beginning of the file.
Syntax: ftell(FILE *fp);

3. rewind() – This function is used to move the file pointer to the beginning of the file. This function is
useful when we open file for update.
Syntax: void rewind(FILE *fp);

void main()
{
FILE *fp1, *fp2;
char ch;
int pos;
clrscr();
if ((fp1 = fopen("File_1.txt","r")) == NULL)
{
printf("\nFile cannot be opened");
return;
}
NS Raju Institute of Technology Page 12
Introduction to Programming (AR23) Unit-V
else
{
printf("\nFile opened for copy...\n ");
}
fp2 = fopen("File_2.txt", "w");
fseek(fp1, 0L, SEEK_END); // file pointer at end of file
pos = ftell(fp1);
fseek(fp1, 0L, SEEK_SET); // file pointer set at start
while (pos--)
{
ch = fgetc(fp1); // copying file character by character
fputc(ch, fp2);
}
getch();
fcloseall();
}

NS Raju Institute of Technology Page 13

You might also like