0% found this document useful (0 votes)
42 views40 pages

PSPC Unit-6

Uploaded by

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

PSPC Unit-6

Uploaded by

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

PSTC UNIT-VI Structures & Unions

6.0 Introduction
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 can be stored in an
array marks[5]. marks[0], marks[1], etc, will store student information like the marks obtained in
various subjects. Suppose we want to store student information in array name, htno, address,
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 language provides a facility
called the structure.

6.1 Definition of structure


A structure is a collection of variables of different types that are logically grouped together and
referred under a single name.
 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.

In C language, a structure can be defined as follows:

struct structure_name
{
data_type member_variable1;
data_type member_variable2;
……
data_type member_variableN;
};

The variables declared inside the structure are known as members of the structure.

For Example
Datatype
Struct student

{
char name[20];
char ht_no[10];
char gender;
float marks;
long int phone_no;
};

Points remember
 The members of the structure may be any of the common data type, pointers, arrays or
even the other structures.
 Member names with in a structure must be different.
 Structure definition starts with the open brace({) and ends with closing brace(}) followed
by a semicolon.

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 1


PSTC UNIT-VI Structures & Unions
 The compiler does not reserve memory any memory when structure is defined. We have
to define the variable to store its information.
6.2 Structure variable
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:

 In the structure declaration


 Using the structure tag // like variable declaration.

In the structure declaration


The structure variable can be declared after the closing brace. Following example shows this.

struct date
{
int dat;
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
{
int dat;
int month;
int year;
};

struct date dob,doj;

6.3 Initialization of structure


We can initialize the values to the members of the structure as:

struct structure_name structure_variable={value1, value2, … , valueN};

 There is a one-to-one correspondence between the members and their initializing values.
 C does not allow the initialization of individual structure members within the
structure definition template.
struct date
{
int dat;
int month;

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 2


PSTC UNIT-VI Structures & Unions
int year;
};

struct date dob={25,12,1998}; or ={.month=9,.year=2019,.dat=19};

Following example shows how to initialize structure in the above method.


#include<stdio.h>
struct student
{
char name[30];
int htno;
char gender;
int marks;
char address[30];
}; Name htno gender marks adress
int main()
{
struct student
st={"XYZ",581,'M',79.5,"Nuzvid"}; 200 210 212 213 217
printf("Student Name:%s\n",st.name);
printf("RollNo:%d\n",st.htno);
printf("Gender:%c\n",st.gender); St
printf("Marks obtained:%d\n",st.marks);
printf("Address:%s\n",st.address); 200
Base address
return 0;
}

Output
Student Name: XYZ
Roll No: 581
Gender: M
Marks obtained:79.5
Address: Nuzvid

6.4 Accessing members of structure


For accessing any member of the structure, we use dot (.) operator or period operator. We can
also use  operator also. when we are accessing structure members through pointers then we use
arrow operator.

Syntax:
structure_variable.membername

Here, structure_variable refers to the name of a structure type variable and member refers
to the name of a member within the structure.

Following example shows how to access structure members


#include<stdio.h>

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 3


PSTC UNIT-VI Structures & Unions
struct date
{
int day;
int month;
int year;
};

int main()
{
struct date dob;
printf("Enter your birthday details\n");
printf("Enter the day:");
scanf("%d",&dob.day);
printf("Enter the month:");
scanf("%d",&dob.month);
printf("Enter the year:");
scanf("%d",&dob.year);
printf("Your date of birth is:");
printf("%d-%d-%d\n",dob.day,dob.month,dob.year); return
0;
}

Output
Enter your birthday details
Enter the day:12
Enter the month:7
Enter the year:1998
Your date of birth is: 12-7-1998

Note: structure is also define local and global..

Local structure Global structure


#include<stdio.h> #include<stdio.h>
void check(); void check();
void main() struct student
{ {
struct student int regid;
{ char name[100];
int regid; float cgpa;
char name[100]; }st;
float cgpa; void main()
}st; {
} check();
void check() }
{ void check()
st.name="Ramesh"; {
printf("%s",st.name); st.cgpa=9.9;

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 4


PSTC UNIT-VI Structures & Unions

} printf("%.1f",st.cgpa);
Output:- }
ERROR Output:-
9.9
Note:-It will give error because here structure
is local.so we can access it only in main
function.

6.5 Nested Structure


We can take any structure as a member of structure. i.e. called structure with in
structure or nested structure.
For example:
struct
{
member 1;
member 2;
……
……
struct
{
member 1;
member 2;
}s_var2;
……
member m;
}s_var1;

For accessing the member 1 of inner structure we write as:


s_var1.s_var2.member1;

Following example illustrates the nested structure


#include<stdio.h>
struct student
{
char name[30];
int htno;
struct date
{
int day;
int month;
int year;
}dob;
char address[10];
};
int main()
{

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 5


PSTC UNIT-VI Structures & Unions
struct student st;
printf("Enter student details\n");
printf("Enter student name:"); scanf("%s",st.name);
printf("Enter rollno:"); scanf("%d",&st.htno); printf("Enter
address:"); scanf("%s",st.address); printf("Enter the day:");
scanf("%d",&st.dob.day); printf("Enter the month:");
scanf("%d",&st.dob.month); printf("Enter the year:");
scanf("%d",&st.dob.year); printf("Student Details\n------------
------\n");
printf("Student Name:%s\n",st.name);
printf("Roll No:%d\n",st.htno);
printf("Date of birth:%d-%d-%d\n",st.dob.day,st.dob.month,st.dob.year);
printf("Address:%s\n",st.address);
return 0;
}

Output
Enter student details
Enter student name: Ramesh
Enter roll no: 1224
Enter address: vizag
Enter the day:15
Enter the month:8
Enter the year:1991
Student Details
-----------------
Student Name: Ramesh
Roll No: 1224
Date of birth is: 15-8-1991
Address: vizag

6.6 Array of structures :


 An array of structures is declared in the same way as we declare an array of a predefined
data type.

Syntax :

struct struct name


{
data_type member;
…………………
…………………..
…………………..
}
struct struct_name struct_var[index];

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 6


PSTC UNIT-VI Structures & Unions
Example:
#include<stdio.h>
struct student
{
int sid;
char name[100];
float marks;
};
int main( )
{
int i;
struct student st[3];
printf(“enter three students details:”);
for(i=0;i<3;i++)
{
printf(“\n enter the students roolno:”);
scanf(“%d”,&st[i].sid);
printf(“\n enter the students Name:”);
scanf(“%s”,st[i].name);
printf(“\n enter the students marks:”);
scanf(“%f”,&st[i].marks);
}
for(i=0;i<3;i++)
{
printf(“Details Of students :”);
printf(“Roll no=%d”,st[i].sid);
printf(“Name=%s”,st[i].name);
printf(“marks =%f”,st[i].marks);
}

OUTPUT:
enter the students roolno: 1224
enter the students name: Ram
enter the students marks: 78.9
enter the students roolno: 1256
enter the students name: Syam
enter the students marks: 45.7
enter the students roolno: 7654
enter the students name: Lava
enter the students marks: 90.9
Details Of students
Roll no=1224
Name=Ram
marks = 78.9
Details Of students
Roll no=Syam
Name=1256

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 7


PSTC UNIT-VI Structures & Unions

marks = 45.7
Details Of students
Roll no=7654
Name=Lava
marks = 90.9

St[0] sid sname marks


st[0].sid st[0].sname st[0].marks

2000 2002 2022

st[1].sid st[1].sname st[1].marks

3000 3002 3022

st[2].sid st[2].sname st[2].marks

4000 4002 4022

0 1 2
2000 3000 4000

1000

1000

St

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 8


PSTC UNIT-VI Structures & Unions

6.7 Arrays in structure:


 We are also declare arrays as structure members , for example, I need three subject marks
for each student then we declare a marks array variable inside the structure.
Example:
struct student
{
int regid;
char name[20];
float marks[3];
};
struct student st[3];

sid sname marks


st[0].sid st[0].sname 5600 St[0].maks[0] St[0].maks[1] St[0].maks[2]

2000 2002 2024 5600 5604 5606

st[1].sid st[1].sname 6000 St[1].maks[0] St[1].maks[1] St[1].maks[2]

3000 3002 3022 6000

st[2].sid st[2].sname 7000 St[2].maks[0] St[2].maks[1] St[2].maks[2]

4000 4002 4022 7000

0 1 2
2000 3000 4000

1000

1000

st

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 9


PSTC UNIT-VI Structures & Unions

6.8 Structures to Functions:-


 A function may access the members of a structure in three ways

passing
structures to
function

passing passing the passing the


individual entire address of
member structure structure

6.8.1 Passing individual member:


 To pass any individual members of the structure to a function we must use the direct
selection operator to refer to the individual member for the actual parameters.
 The called function does not know it the two variable are ordinary variable or structure
member
Ex:-
#include<stdio.h> #include<stdio.h>
struct prgm typedef struct
{ {
int x; int x;
int y; int y;
}; }student;
void add(int,int); void add(int,int);
void main() void main()
{ {
struct prgm p={24,7}; student p={24,7};
add(p.x,p.y); add(p.x,p.y);
} }
void add(int a,int b) void add(int a,int b)
{ {
printf("%d+%d=%d",a,b,a+b); printf("%d+%d=%d",a,b,a+b);
} }

Output:- Output:-
24+7=31 24+7=31

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 10


PSTC UNIT-VI Structures & Unions

6.8.2 Passing entire structure :


 We can pass an entire structure as a function argument when a structure is passed as an
argument. It is using call by value method.
 A copy of each member of structure is made. This is a very complicated especially when
structure is very big or the function is called frequently.
 In such a situation passing and working with pointers may be more efficient.
Syntax:-

struct struct_name fun_name(struct struct_name struct var);

#include<stdio.h> #include<stdio.h>
struct prgm typedef struct
{ {
int x; int x;
int y; int y;
}; }student;
void add(struct prgm ); void add(student);
void main() void main()
{ {
struct prgm p={24,7}; student p={24,7};
add(p); add(p);
} }
void add(struct prgm pr) void add(student s)
{ {
printf("%d+%d=%d",pr.x,pr.y, printf("%d+%d=%d",s.x,s.y,s.x+s.y);
pr.x+pr.y); }
}
Output:-
Output:- 24+7=31
24+7=31

Typedef in structures:-

#include<stdio.h> #include<stdio.h>
typedef struct student typedef struct student
{ {
int x; int x;
int y; int y;
}; }a;
void main() void main()
{ {
typedef struct student a; a s={27,3};
a s={27,3}; printf("%d",s.x+s.y);
printf("%d" ,s.x+s.y); }
}

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 11


PSTC UNIT-VI Structures & Unions

6.8.3 Passing structures through pointers (pointers to structures):-

 Passing large structures to function using the call by value method is very inefficient.
 It is professional to run structure through pointer
 It is possible to create a pointer to almost any type in C ,including user defined types
Syntax:-
struct struct_name
{
datatype member_name;
..............;
...............;
}*ptr;
Or
struct struct_name *ptr;

Ex:-
#include<stdio.h>
typedef struct student
{ Output
int sid; enter sid=123
char name[20]; enter name1=Ramesh
float marks; enter marks1=9.8
}; enter sid2=456
void main() enter name2=abc
{
typedef struct student st; enter marks2=9.5
st *ptr1,*ptr2,st1,st2;
ptr1=&st1; Student details=
ptr2=&st2; sid1=123
printf("Enter sid1="); name1=Ramesh
scanf("%d",&ptr1->sid); marks1=9.8
printf("Enter name1=");
scanf("%s",&(ptr1->name));
printf("Enter marks1="); sid2=456
scanf("%f",&(ptr1->marks)); name2=abc
printf("Enter sid2="); marks2=9.5
scanf("%d",&ptr2->sid);
printf("Enter name2=");
scanf("%s",&(ptr2->name));
printf("Enter marks2=");
scanf("%f",&(ptr2->marks));
printf("\nStudent details=\n");
printf("sid=%d\nsname=%s\nmarks=%.1f\n\n",ptr1->sid,ptr1->name,ptr1->marks);
printf("sid=%d\nsname=%s\nmarks=%.1f\n",ptr2->sid,ptr2->name,ptr2->marks); }

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 12


PSTC UNIT-VI Structures & Unions

6.9 Self-referential structure


A self-referential is one which contains a pointer to its own type. This type of structure is
also known as linked list. For example
struct node
{
int data;
struct node *nextptr;
};

Defines a data type, struct node. A structure type struct node has two members-integer member
data and pointer member nextptr. Member nextptr points to a structure of type struct node – a
structure of the same type as one being declared here, hence the term “self-referential structure”.
Member nextptr referred to as a link i.e. nextptr can be used to tie a structure of type struct node
to another structure of the same type. self referential structures can be linked together to form a
usual data structures such as lists etc.

#include<stdio.h>
struct student
{
char name[30];
int age;
char address[20];
struct student *next;
};
int main()
{
struct student st1={"Ramesh",24,"Vizag"};
struct student st2={"Rajesh",21,"Nuzvid "};
struct student st3={"Mahesh",22,"Hyd"};
st1.next = &st2;
st2.next = &st3;
st3.next = NULL;
printf("Student Name:%s\tAge:%d\tAddress:%s\n",st1.name,st1.age,st1.address);
printf("Student 1 stored at %x \n",st1.next);
printf("Student Name:%s\tAge:%d\tAddress:%s\n",st2.name,st2.age,st2.address);
printf("Student 2 stored at %x \n",st2.next);
printf("Student Name:%s\tAge:%d\tAddress:%s\n",st3.name,st3.age,st3.address);
printf("Student 3 stored at %x \n",st3.next); return 0;
}
Output
Student Name:Ramesh Age:24 Address: Vizag
Student 1 stored at 88f0
Student Name:Rajesh Age:21 Address:Nuzvid
Student 2 stored at 8854
Student Name:Mahesh Age:22 Address: Hyd
Student 3 stored at 0

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 13


PSTC UNIT-VI Structures & Unions

To Create Structure using malloc( ) :


#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i;
printf("Enter no of students=");
scanf("%d",&n);
struct student
{
int regid;
char name[100];
float cgpa; Output:-
}; Enter no of students=2
struct student*ptr;
ptr=(struct student*)malloc(n*sizeof(struct student)); enter REGID=123
if(ptr==NULL) enter name=Ramesh
{
printf("no storage left on your device"); enter cgpa=9.8
exit(1); enter REGID=456
}
else enter name=abc
{ enter cgpa=9.5
for(i=0;i<n;i++)
{
printf("enter REGID="); Student details=
scanf("%d",&(ptr+i)->regid); REGID=123
printf("enter name=");
scanf("%s",&(ptr+i)->name); name=Ramesh
printf("enter cgpa="); cgpa=9.8
scanf("%f",&(ptr+i)->cgpa);
}
Printf(“\nStudent details=”); REGID=456
for(i=0;i<n;i++)
{ name=abc
printf("regid=%d\n",(ptr+i)->regid); cgpa=9.5
printf("name=%s\n",(ptr+i)->name);
printf("cgpa=%.1f\n\n",(ptr+i)->cgpa);
}
}
}

Note:-
If pointer variable is pointing to the structure we are using ->operator to read the structure
members.

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 14


PSTC UNIT-VI Structures & Unions

Unions
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 where as the members of union
has the same memory location.
 We can assign values to only one member at a time, so assigning value to another
member that time has no meaning.

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
union
{
member 1;
member 2;
……
……
member N;
};

Following example shows how to declare union and accessing the members of union

#include<stdio.h> Example 2:
union student
{ #include<stdio.h> a, b
char name[30]; Union un
int age;
{ 10 20
};
int main() int a,b;
{ }var; 2046 (2 bytes )
union student st;
clrscr(); int main( )
printf("Enter student name:"); {
scanf("%s",st.name);
var.a=10;
printf("Student Name:%s, age=
%d\n",st.name,st.age); st.age=24; pf(“A=%d \t B=%d”,var.a,var.b);
printf("Student Name:%s, age= var.b=20;
%d\n",st.name,st.age);
getch(); pf(“A=%d \t B=%d”,var.a,var.b);
return 0; }
}
OUTPUT:
Output
Enter student name: Ramesh A=10 B=10
Student Name: Ramesh, age= 26966 A=20 B=20
Student Name: ¶ , age= 24

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 15


PSTC UNIT-VI Structures & Unions

Look at the output


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 this time only student‟s age is displayed.

Following figure illustrates how members of structure and union are stored.
struct student
{
char name[15];
int age;
};

Fig. Storage in structure


union student
{
char name[15];
int age;
};

Fig. Storage in union

Comparison between structure and union

S.No Structure Union


1. Stores heterogeneous data Stores heterogeneous data
2. Members are stored separately in Members are stored in same memory
memory locations. location.
3. In structures all the members are In union only one member is available
available. at a time.
4. Occupies more memory when Occupies less memory when compared
compared to union with structure.
5. Size of the structure is the total Size of the union is the size of the
largest data type member in the union. All
memory space required by its members the elements share same memory

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 16


PSTC UNIT-VI Structures & Unions
location.All the elements we cannot
process.
Ex:
struct student
{
int sid; Ex:
char sname[10]; unioin student
float smarks; {
}; int sid;
char sname[10];
Struct student st; float smarks;
};
sid sname smarks
union student st;
sid ,sname , smarks

2bytes 10 bytes 4 bytes


10 bytes

Comparison between array and structure


S.No Array Structure
1. Stores homogeneous data Stores heterogeneous data
2. Two arrays of same type cannot be Structures of same type can be
assigned to one to one assigned.
3. Arrays can be initialized Structures cannot be initialized
4. Array is a combination of elements Structure is a combination of members
5. Multidimensional arrays are possible No in case of structures
6. No operators are required to access Operators like „.‟ or „->‟ are required to
elements of an array access members of a structure.
7. An element in the array referenced by Members in a structure will be
specifying array name and its position referenced as
in the array. For example: a[5] structurename.membername
8. C treats array names as pointers Structure name is not treated as
pointer variable.
9. When an array name is passed as When an structure name is passed as
argument to function, it is call by argument to function, it is call by value.
reference.

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 17


PSTC UNIT-VI Structures & Unions

Array of Unions:
#include<stdio.h>
union num
{
int a; OUTPUT:
int b; the a and b values in index 0 is 20 and 20
}; the a and b values in index 1 is 40 and 40
int main() the a and b values in index 0 is 60 and 60
{
int i;
union num arr[3];
arr[0].a=10;
arr[0].b=20;
arr[1].a=30;
arr[1].b=40;
arr[2].a=50;
arr[2].b=60;
for(i=0;i<3;i++)
{
printf("\n the a and b values in index %d is %d and %d ",i,arr[i].a,arr[i].b);

}
return 0;
}

Union inside the structures:

#include<stdio.h>
struct student
{
union st
{
char name[20];
int sid;
}st1;
int marks;

};
int main()
{
struct student st;
char choice;
printf("\n you can enter the NAME or ID:");

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 18


PSTC UNIT-VI Structures & Unions
printf("\n Do you want Ur results by Name Enter (Y) :");
scanf("%c",&choice);
if(choice=='y'||choice=='Y')
{
printf("\n enter Name:");
scanf("%s",st.st1.name); // or st.name
printf("\n enter marks:");
scanf("%d",&st.marks);
printf("\ Student Name:%s",st.st1.name);
printf("\nStudent matrks:%d",st.marks);
}

else
{
printf("\n enter sid:");
scanf("%d",&st.st1.sid);
printf("\n enter marks:");
scanf("%d",&st.marks);
printf("\ Student Id:%d",st.st1.sid);
printf("\nStudent matrks:%d",st.marks);
}
}

OUTPUT:
you can enter the NAME or ID:
Do you want Ur results by Name Enter (Y): Y
Enter name: Ram
Enter marks: 24
Student Name: Ram
Student Marks: 24

you can enter the NAME or ID:


Do you want Ur results by Name Enter (Y): N
Enter ID: 1224
Enter marks: 78
Student ID:1224
Student Marks: 78

Note: When we are declare the union inside the structure , no need to declare variable for union,
by accessing union members it also possible to access through structure variable.

St.un.member or st.member

Structure.union.member

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 19


PSTC UNIT-VI Structures & Unions

Structures inside the Unions:


#include<stdio.h>
struct a
{
int marks;
int sid;
};
struct b
{
char name[20];
int marks;

};
union Student
{
struct a A;
struct b B;

};
int main()
{
union Student s;
char ch;
printf("\n you can enter the NAME or ID:");
printf("\n Do you want Ur results by Enter Name or Roll No (N/R) :");
scanf("%c",&ch);
if(ch=='N'||ch=='n')
{
printf("\n enter Name:");
scanf("%s",s.B.name);
printf("\n enter marks:");
scanf("%d",&s.B.marks);
printf("\ Student Name:%s",s.B.name);
printf("\nStudent matrks:%d",s.B.marks);
}
if(ch=='R'||ch=='r')
{
printf("\n enter RoolNo:");
scanf("%d",&s.A.sid);
printf("\n enter marks:");
scanf("%d",&s.A.marks);
printf("\ Student ID:%d",s.A.sid);
printf("\nStudent matrks:%d",s.A.marks);
}
return 0;

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 20


PSTC UNIT-VI Structures & Unions
}

OUTPUT:
you can enter the NAME or ID:
Do you want Ur results by Enter Name or Roll No: (N/R) : N
Enter name: Ram
Enter marks: 24
Student Name: Ram
Student Marks: 24

you can enter the NAME or ID:


Do you want Ur results by Enter Name or Roll No: (N/R) : N
Enter ID: 1224
Enter marks: 78
Student ID:1224
Student Marks: 78

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 21


6.10 FILES introduction :
File is a collection of bytes that is stored on secondary storage devices like hard disk. There
are two kinds of files in a system. They are,
1. ASCII Text Files
2. Binary Files

A file has a beginning and an end; it has a current position, typically defined as on many
bytes from the beginning. You can move the current position to any other point in file. A
new current position can be specified as an offset from the beginning the file.

Types of files:

ASCII Text Files


 A text file can be a stream of charact ers that a computer can process sequentially.
 It is processed only in forward direction.
 It is opened for one kind of operation (reading, writing, or appending) at any give
time.
 It can read only one character at a time.

Binary files :
 A binary file is collection of bytes.
 In „C‟ both a both a byte and a character are equivalent.
 A binary file is also referred to as a character stream, but there are two essential
differences.

6.11 File streams


A stream is a series of bytes of data flow from your program to a file or vice-versa. A
stream is an abstract representation of any external source or destination for data, so the
keyword, the command line on your display and files on disk are all examples of stream. „C‟
provides numbers of function for reading and writing t o or from the streams on any external
devices. There are two formats of streams which are as follows:
1. Text Stream
2. Binary Stream

Text Stream
 It consists of sequence of characters, depending on the compilers.
 Each character line in a text stream may be terminated by a newline character.
 Text streams are used for textual data, which has a consistent appearance from one
environment to another or from one machine to another.

Binary Stream
 It is a series of bytes.
 Binary streams are primarily used for non-textual data, which is required to keep exact
contents of the file.

6.12 File Operations


In C, you can perform four major operations on the file, either text or binary:
1. Opening a file
2. Closing a file
3. Reading a file
4. Writing in a file

6.12.1 Opening a file


To perform any operation (read or write), the file has to be brought into memory from the
storage device. Thus, bringing the copy of file from disk to memory is called opening the file.

The fopen() function is used to open a file and associates an I/O stream with it. The general
form of fopen() is
M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 1
fopen(const char *filename, const char * mode);

This function takes two arguments. The first argument is the name of the file to be opened
while the second argument is the mode in which the file is to be opened.

NOTE: Before opening a file, we have to create a file pointer that is created using FILE
structure is defined in the “stdio.h” header file.

For example
FILE *fp;
if(fp = fopen(“csefile.txt”,”r”)) == NULL)
{
printf(“Error opening a file”);
exit(1);

}
This opens a file named csefile.txt in read mode.

File opening modes

Mode Meaning

R Open a text file for reading only. If the file doesn‟t exist, it returns null.

Opens a file for writing only.


If file exists, then all the contents of that file are destroyed and new
W fresh blank file is copied on the disk and memory with same name.
If file doesn‟t exists, a new blank file is created and opened for writing.
Returns NULL if it is unable to open the file
Appends to the existing text file.
Adds data at the end of the file.
A
If file doesn‟t exists then a new file is created.
Returns NULL if it is unable to open the file.
Rb Open a binary file for reading

Wb Open a binary file for reading

Ab Append to a binary file

r+ Open a text file for read/write

w+ Opens the existing text file or Creates a text file for read/write

r+b Open a binary file for read/write

w+b Create a binary file for read/write

a+b Append a binary file for read/write

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 2


6.12.2 Closing a file
To close a file and dis-associate it with a stream, use fc lose() function. It returns zero if
successful else returns EOF if error occurs. The fc loseall() closes all the files opened
previously. The general form is:

fclose(file pointer);

6.13. Reading from the text file:


When we want to read contents from existing file, then we require opening that file into
read mode that means “r” mode. To read file follow the below steps

1. Initialize the file variable


2. Open a file in read mode
3. Accept information from file
4. Write it into the output devices
5. Close the file
Example
#include<stdio.h>
int main()
{
FILE *fp;

char ch;
clrscr();
fp=fopen("file1.c","r"); // file opened in read mode
if(fp==NULL)
printf("Unable to open test.txt");
else
{
do
{
ch = getc(fp);
putchar(ch);
}while(ch!=EOF);
fclose(fp);
}
getch();
return 0;
}

Output
Welcome to Files. You opened a file name test.txt
Note: EOF means End of File that denotes the end-of-file.

Function for reading from the text files:


 There are five functions to read text from the file.

1. fscanf()
2. fgets()
3. fgetc( )
4. fread()
5. fgetw()

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 3


fscanf ():-The scanf() is used to read formatted data from the stream.
Prototype:-
int scanf(FILE *stream, const char *format,------)
 It is used to read data from the stream and store from according to the parameter
format.
Type Specifiers:-
 C  for single character
 D decimal value
 E,e,F,g,G for floating
 Octal
 S String
 U for unsigned
 X,x hexadecimal
Note:-
The fscanf( ) function is similar to the scanf( ) function, except that the first argument of
fscanf() specified as a stream from which to read, whereas scanf() can only read from
standard.
Ex:-
main()
{
FILE *fp;
char name[70];
int sid;
fp=fopen(“student.txt”,”r”);
if(fp==NULL)
{
printf(“Unable to open”);
exit(1);
}
printf(“Enter name and roll no:”);
fscanf(stdin,”%s %d”,name, &sid);
printf(Name:%s \Roll no=”%d”,name,sid);
fscanf(fp, “%s %d”, name, &sid);
printf(“In name:%s Roll number = %d”,name,sid);
fclose(fp);
}

fgets( ) :
The function fgets() stands for file get string.
 The function is used to get string from a stream.
Syntax:-
char* fgets(char *str, int size, *stream);

 This function reads the a line of characters/


 The fgets() function reads at most one less than the no. of characters specified by size
from the given stream and stores them in the string str.
 It is terminated as soon as it encounters either newline character, EOF or any other
error.
 It is a new line character is encountered it is retained.
 When all the characters are read without any error, a ‘\0’ character is appended to the
end of the string.
 Difference between gets and fgets all most same but the difference is

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 4


gets Fgets
 Infinite size and stream of stdin.  Specified size.

 When encounters a newline  When encounters a newline it


character, it does not retain it. retains.

 On successfully completes ,the fgets() will return str.


 On failure, the stream is at EOF.
 If fgets() encounters any error while reading, the error indicator for stream will be set
a null pointer.
Ex:
#include<stdio.h>
main() while(fgets(str,70,fp)!=NULL)
{ {
FILE *fp; printf(“%s”,str);
char str[70]; }
fp=fopen(“abc.txt”,”r”); printf(“File read computer”);
if(fp==NULL) fclose(fp);
{
printf(“Unable to open“);
exit(1);
}

fgetc( ):-
 The fgetc( ) function returns next character from streams.
Prototype:- int fgetc(FILE *stream);
 fgetc() returns the character read as an int.
 fgetc() reads a single character from the current position of a file. After reading the
character, the function increments the associated file pointer to point to the next
character.
 If the stream is reached the End Of File, the EOF indicator for the stream for the
steam is set.
Ex:
#include<stdio.h>
main()
{
FILE *fp;
int ch;
fp=fopen(“file.txt”,”r”);
if(fp==NULL)
{
printf(“Unable to open”);
}

while((ch=fgetc(fp))!=EOF)
{
printf(“%c”,ch);
}
}

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 5


fread( ):-
 The fread() function is used to read data from a file.
Prototype : int fread(void *str, size_t size, size_t num, FILE *stream);

 The function on successful, fread() returns the no. of bytes successfully read. The no.
of objects will be less than num if a read error or end of file is encountered.
 If size or num is 0, fread() will return 0.
Note:-
The fread() function does not distinguish between end-of-file and error. The program
must use feof and ferror to determine which of the two occurs.
Ex:
#include<stdio.h>
main()
{
FILE *fp;
char str[20];
fp=fopen(“Letters.txt”,”r+”);
if(fp==NULL)
{
printf(“Unable to open”);
exit(1);
}
fread(str,1,10,fp);
str[10]=’\0’;
printf(“\n The first character of a file %s”,str);
fclose(fp);
}

fgetw( ):-
 The fgetw() is used to read an integer from the file stream.
Prototype: int fgetw(fp);
#include<stdio.h>
int main()
{
int num;
FILE *fp;
Fp=fopen(“Num.txt”,”r”);
printf(“The numbers in the file are:”);
num=getw(fp);
while(num!=EOF)
printf(“%d”,num);
return 0;
}

6.14 Writing to the file :


When we want to write new data to the file, then we require opening that file in write mode
that means “w” mode. To write in to the file follow the below steps

1. Initialize the file variable


2. Open a file in write mode
3. Accept information from the user
4. Write in to the file
5. Close the file

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 6


<stdio.h>
Example
#include
int main()
{
FILE *fp;
char c;
// file opened in write mode

fp = fopen("test.txt", "w");
printf("Enter your Input\n");
while((c =getchar()) != EOF) //writing data to the file
putc(c,fp);
fclose(fp);

printf("\nYou have entered\n");


fp = fopen("test.txt","r");
while((c =getc(fp)) != EOF) //reading data from file
printf("%c ",c);
fclose(fp);
return 0;
}
Output
Enter your Input
Hi Students…! How are you?
All the best for your end exams. (press CTRL+Z for stopping)

You have entered


Hi Students…! How are you?
All the best for your end exams.

Functions to write a text to file:


 There are five functions to write text into files they are :
1. fprintf( )
2. fputs( )
3. fputc( )
4. fwrite( )
5. fputw( )

(1) fprintf():-

 The fprintf() is used to write formatted output to stream. It same as printf( ), but here
first argument is file pointer.
 This function write the information to file.

Prototype : int fprintf(FILE *stream, const char *formal);

#include<stdio.h>
main()
{
FILE *fp;
int i,n;
char sname[20];
int sid;

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 7


float smarks;
printf(“Student details:”);
for(i=0;i<n;i++)
{
puts(“Enter student sID:”);
scanf(“%d”,&sid);
puts(“Enter student Name:”);
scanf(“%d”,sname);
puts(“Enter student marks:”);
scanf(“%f”,smarks);
printf(fp, “sid:%d\t Name:%s \t marks:%f \t”, sid,sname,smarks);
}
fclose(fp);
}

fputs():-

The opposite of fgets() is fputs(). The fputs() is used to write a line to a file.
Syntax:-

int fputs(const char *str, File *stream);


Ex:-

#include<stdio.h>
main()
{
FILE *fp;
char greeting[100];
fp=fopen(“wishes.txt”,”w”);
if(fp==NULL)
printf(“\n Enter your wishes”);
gets(greeting);
fflush(stdin);
fputs(greeting, fp);
fclose(fp);
}

fputc():-
 It is opposite to fgetc() and is used to write a character to the stream.

Syntax:- int fputc(int c, FILE *stream);

 On successful completion, fputc() will return the value it has written otherwise error,
the function will return EOF.

#include<stdio.h>
main()
{
FILE *fp;
char welcome[100];
int i;
fp=fopen(“Welcome.txt”,”w”);
if(fp==NULL)
printf(“\n Provide welcome message”);
gets(welcome);
for(i=0;i<feedback[i];i++)
fputc(“feedback[i]”, fp);
M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 8
fclose(fp);
}
fwrite():-

 It is used to write data to a file.

Prototype: int fwrite(const void *str, size_t, size, size_t count, FILE *stream);

 The fwrite() function will write objects of size specified by size.


 The file position indicator for the stream will be advanced by two no. of bytes
successfully written.
 fwrite() function returns the no. of successfully written. The no. of objects will be
less than count if an error is encountered.
 If size or count is 0, fwrite() will return 0.

Ex:-
#include<stdio.h>
main()
{
FILE *fp;
size_t count;
char str[]=”GOOD MORNING”;
fp=fopen(“Welcome.txt”,”wb”);
count=fwrite(str, 1, strlen(str), fp);
printf(“\n%d bytes were written to the file”,count);
fclose(fp);
return 0;
}

fputw():-

The putw() is used to write an integer to file system.

Syntax :
int fputw(word, fpt);
#include<stdio.h>
main()
{
FILE *fp;
int i, n, val;
fp=fopen(“file1”, “wb”);
if(fp==NULL)
{
printf(“File does not exists”);
exit(1);
}
else
{
printf(“\nEnter the no. of values to be stored:”);
scanf(“%d”,&n);
printf(“\nEnter the values:”);
for(i=1;i<=n;i++)
{
scanf(“%d”,&val);
fputw(val, fr);
}
}}
M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 9
6.15 RANDOM ACCESS FILES:
 We can access the file in any place that’s from beginning , ending and middle of the
file also.
1. fseek( )
2. ftell( )
3. rewind( )
4. fgetpos( )
5. fsetpos( )

We will be able to change file pointer position using these functions.

(1) fseek():-

The function fseek() is used to reposition a binary stream.

Prototype:-

int fseek(FILE *stream, long offset, int origin);

• fseek() is used to set the file position pointer for the given stream.
• It is used to move the file pointer to different position using fseek function.

Syntax:-

fseek(file pointer, displacement, pointer position);

File Pointer --> It is the pointer which points the file.


Displacement--> It is positive or negative. This is the no. of bytes which one skipped
backward (if negative) or forward (if positive) from the current position that is attached with
long integer.

Pointer Position:-

 This sets the pointer position in the file. Origin values should have one of the
following.

0 Beginning of file SEEK_SET


1 Current position SEEK_CUR
2 End of file SEEK_END

Ex:-

fseek(fp, 10, SEEK_SET) OR fseek(fp, 10, 0);


fseek(fp, -10, SEEK_END) OR fseek(fp, -10, 2);
fseek(fp, 2, SEEK_CUR) OR fseek(fp, 2, 1);

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 10


Program:- OUTPUT:
abc.txt
#include<stdio.h> RGUKT NUZVID
main() RGUKT ANDHRA PRADESH
{
FILE *fp;
fp=fopen(“abc.txt”,”w+”);
fputs(“RGUKT NUZVID”, fp);
fseek(fp, 7, SEEK_SET);
fputs(“ANDHRA PRADESH”, fp);
fclose(fp);
return 0;
}

ftell():-

The ftell() function used to know the current position of file pointer.

Syntax:-

long int ftell(File Pointer);

Here, file pointer points to the file whose file position indicator has to be determined.

• If Successful, ftell() returns current file position.


• If Fail, it returns -1.

Ex:-
Hello CSE
printf(“%d”, ftell(fp)); --> 9

#include<stdio.h>
main()
{
FILE *fp;
int len;
fp=fopen(“file.txt”,”r”);
fseek(fp, 0, SEEK_END);
len=ftell(fp);
printf(“%d”, len);
fclose(fp);
}

rewind():- rewind() is used to move the file pointer to the beginning of the file.

Syntax:- rewind(fp);
where fp is a file pointer.

Hello CSE rewind(fp) Hello CSE

fp fp

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 11


• rewind() is equivalent to calling fseek() with following arguments.
fseek(fp, 0, SEEK_SET);
#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp=fopen(“abc.txt”, “r”);
while((ch=fget(fp))!=EOF)
{
printf(“%c”, ch);
}
rewind(fp);
}

fgetpos():-
 The fgetpos() is used to determine the current position of the file pointer.

Syntax:-

int fgetpos(FILE *stream, fpos_t *pos);

stream --> This is a point to a file.


Pos --> Pointer to fpos_t object.

 The function returns zero on success, else non-zero value in case of an error.
 getpos( ) can be used by two fsetpos() to return to this same position.

fsetpos():-

The fsetpos() is used to move the file position indicator of a stream to the location
indicated by the information obtained in position by making a call to the fgetpos().

Syntax:-
int fsetpos(file *stream, const fpos_t pos);

• Stream is a file pointer.


• The pos is a position given by function fgetpos.
• This function return zero if successful.
• It returns a non-zero value and sets the global variable errno to positive value.

#include<stdio.h>
main()
{
FILE *fp;
fpos_t position;
fp=fopen(“file.txt”, “w+”);
fgetpos(fp, &position);
fputs(“Hello CSE!”, fp);
fsetpos(fp, &position);
fputs(“This is going to override previous content”, fp);
}

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 12


6.16 Remove( ):-
 The function remove() is used to erase a file.
Prototype:
int remove(const, char *filename);
 On success, it return 0.
 On failure, it returns non-zero value.
Ex:
#include<stdio.h>
main()
{
remove(“abc.txt”);
return 0;
}

6.17 Renaming the file:-


It is used to rename a file.
Syntax:-
int remove(const char *old name, const char *new name);
• On success, it return 0.
• On failure, it return non-zero.
#include<stdio.h>
main()
{
int success=0;
success=rename(“abc.txt”, “xyz.txt”)
if(success==0)
{
printf(“The file name renamed”);
}
else
{
printf(“File name not changed”);
}
}

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 13


PSTC UNIT-VI Files

M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 14


PSTC UNIT-VI typedef & enum

Type definition (typedef)


 The typedef keyword enables the programmer to create a new data type(duplicate data
type) from existing data type.
 No new name is created, rather than alternate name is given to a known data type

Syntax: typedef existing_data_type new_data_type

Ex : typedef int cse

 Here, cse is a new name of data type int.


 By using typedef, we can create synonymous for available data type.
 typedef statement doesn’t occupy any memory ,it simply define new type.
 it is also local and global.

Example:
#include<stdio.h>
int main( )
{
typedef int cse;
cse a=10,b=20,c=30;
printf(“sum:%d”,a+b+c);
}

OUTPUT: sum: 30

typedef using Array:


#include<stdio.h>
int main( )
{

int i=0;
typedef int Array[5]; // Array is a new name for integer array with specified size;
Array x={1,2,3,4,5};
printf(“Array elements are:”);
for( i=0;i<5;i++)
{

M.Ramesh,Dept of CSE, IIIT-Nuzvid. Page 1


PSTC UNIT-VI typedef & enum

printf(“%d\n”,x[i]); OUTPUT:
1
} 2
} 3
4
5

 In above program int changes to new data type i.e Array , it stores the array elements
with specified size.
 When we are declare the variable with Array data type . that variable holds the elements .
 Array x; x is a variable it holds the five elements.

typedef using Structures:


 We know that, the structure data type have two words i.e first one struct keyword and
name, both two words together a structure data type.
 Here when space occurred between two words peoples may think both are different
keywords. To simplify the structure datatype as a single word we can use the typedef
statement.
 typedef using in structures in two ways.1. after defining the structure 2. Along with
structure definition.

Ex: Ex:

struct student typedef struct


{ {
int sid; int x;
char name[20]; int y;
float marks; } student; // new name for struct
};
main( )
typedef struct student std; // std is a new {
name for student st={10,20};
struct pf(“%d”,st.x+st.y);
datatype }

std s; // declaration of struct variable Here no need to provide structure name,


and here student is a not a variable. It is a
new name for struct data type. student is a
data type.

M.Ramesh,Dept of CSE, IIIT-Nuzvid. Page 2


PSTC UNIT-VI typedef & enum

typedef using in pointers:

 In c language, there is a no data type for strings . so here taking a character


type it want change to string data type.

Ex:-
#include<stdio.h>
typedef char* string;
char* read(void);
OUTPUT:
void main( )
Enter Name: CSE
{ Welcome CSE
string name;
name=read( );
printf(“Welcome %s”name);
}
string read( )
{
string name;
printf(“Enter Name:”);

gets(name);
return name;
}

M.Ramesh,Dept of CSE, IIIT-Nuzvid. Page 3


PSTC UNIT-VI typedef & enum

Enumerated Data type:-


 User defined data type based on standard integer.
 Working with a set of elements using constant integer values.
 The functionality of a particular element we are accessing just with help of constant integer
value called as enum.
 It contains set of named integer constant. Each integer value is assigned an identifier.
 It provide symbolic name to make the program more readable.
Syntax:-

enum enumeration name {identifier1, ------, identifier n};

 The enum keyword basically used to declare and initialize a sequence of integer
constants. Here enumeration name is optional.
Ex:-

enum E1CSE{CSE1, CSE2, CSE3, CSE4, CSE5}; ouput : 1,2,3,4,5

enum E1CSE{CSE1=2, CSE2, CSE3=10, CSE4, CSE5=24}; ouput : 2,3,10,11,24

Rules:-

 An Enumeration list may contain duplicate constant values. Therefore, two different
identifiers may be assigned the same value.
 The identifiers in the enumeration list must be different from other identifiers in the same
scope with same visibility including ordinary variable names and identifiers in other
enumeration lists.
 Enumeration names follow the normal scoping rules. So, every enumeration must be
different from other enumeration, structures and unions.
Ex:-

#include<stdio.h>

int main()

enum E1CSE{CSE1=2, CSE2, CSE3=10, CSE4, CSE5=24};

prinnf(“\n CSE1=%d”,CSE1);

prinnf(“\n CSE2=%d”,CSE2);

prinnf(“\n CSE3=%d”,CSE3);

M.Ramesh,Dept of CSE, IIIT-Nuzvid. Page 4


PSTC UNIT-VI typedef & enum

prinnf(“\n CSE4=%d”,CSE4);

prinnf(“\n CSE5=%d”,CSE5);

return 0;

OUTPUT:
CSE1=2
CSE2=3
CSE3=10
CSE4=11
CSE5=24

Typedef with num:-

typedef enum E1CSE E2CSE;

Enumeration type conversion:-

enum colors{red, blue, black, green, yellow, purple, white};

enum colors c;

c=black+white

2 + 6 = 8

Two things

 To declare c as int
 Cast the right handisde of
c=enum colors(black+white);

c=black;

//c=2; // error

c=(enum colors) 2;

enum colors{r,b,b,g,y,p,w};

enum colors c; scanf(“%d”,&c); printf(“%d = %d”, c);

M.Ramesh,Dept of CSE, IIIT-Nuzvid. Page 5

You might also like