0% found this document useful (0 votes)
120 views108 pages

Unit 5 PDF

The program defines a structure called student with members name, roll and mark. It declares a variable s of type student. It reads the name, roll and mark of a student using scanf and stores it in the structure variable s. Finally, it displays the stored data using printf.

Uploaded by

bhuvan8hopkins
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)
120 views108 pages

Unit 5 PDF

The program defines a structure called student with members name, roll and mark. It declares a variable s of type student. It reads the name, roll and mark of a student using scanf and stores it in the structure variable s. Finally, it displays the stored data using printf.

Uploaded by

bhuvan8hopkins
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/ 108

SRM

INSTITUTE OF SCIENCE AND TECHNOLOGY,


CHENNAI.

18CSS101J – Programming for Problem Solving


Unit V
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

COURSE LEARNING RATIONALE


(CLR)
The purpose of learning this course is to:
Think and evolve a logically to construct an algorithm into a flowchart and
CLR -1: a pseudocode that can be programmed
Utilize the logical operators and expressions to solve problems in
CLR -2: engineering and real-time

CLR -3: Store and retrieve data in a single and multidimensional array
Utilize custom designed functions that can be used to perform tasks and
CLR -4: can be repeatedly used in any application
Create storage constructs using structure and unions. Create and Utilize
CLR -5: files to store and retrieve information
Create a logical mindset to solve various engineering applications using
CLR -6: programming constructs in C
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

COURSE LEARNING
OUTCOMES (CLO)
At the end of this course, learners will be able to:
Identify methods to solve a problem through computer programming. List
CLO -1: the basic data types and variables in C
Apply the logic operators and expressions. Use loop constructs and
CLO -2: recursion. Use array to store and retrieve data
Analyze programs that need storage and form single and multi-dimensional
CLO -3: arrays. Use preprocessor constructs in C
Create user defined functions for mathematical and other logical operations.
CLO -4: Use pointer to address memory and data
Create structures and unions to represent data constructs. Use files to store
CLO -5: and retrieve data
Apply programming concepts to solve problems. Learn about how C
CLO -6: programming can be effectively used for solutions
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

LEARNING RESOURCES

S. No TEXT BOOKS

Zed A Shaw, Learn C the HardWay: Practical Exercises on the Computational


1.
SubjectsYou Keep Avoiding (Like C), AddisonWesley, 2015

W. Kernighan, Dennis M. Ritchie,The C Programming Language, 2nd ed.


2.
Prentice Hall, 1996

3. Bharat Kinariwala,Tep Dobry, Programming in C, eBook

4. http://www.c4learn.com/learn-c-programming-language/
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

UNIT V
INTRODUCTION
Initializing Structure, Declaring Structure variable- Structure using
typedef, Accessing members – Nested structure Accessing
elements in a structure array – Array of structure Accessing
elements in a structure array –Passing Array of Structure to
function- Array of Pointers to structures- Bit Manipulation of
structure and pointer to structure – Union Basic and declaration –
Accessing Union Members Pointers to union
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

UNIT V
INTRODUCTION
Dynamic memory allocation, malloc, realloc , free – Allocating
Dynamic Array- Multidimensional array using dynamic
memory allocation- file: opening, defining, closing, File Modes,
File Types- Writing contents into a file – Reading file contents –
Appending an existing file- File permissions and rights-
changing permissions and rights.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

INTRODUCTION TO STRUCTURE
• Problem:
– How to group together a collection of data items
of different types that are logically related to a
particular entity??? (Array)
Solution: Structure
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

STRUCTURE

❑ A Structure is a collection of variables of different data types under a


singlename.
❑ The variables are called members of the structure.
❑ The structure is also called a user-defined data type.

8
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Defining a Structure
• Syntax:
struct structure_name
{
data_type member_variable1; data_type
member_variable2;
………………………………; data_type member_variableN;
};
Once structure_name is declared as new data type, then variables of that typecan be
declared as:
struct structure_name structure_variable;
Note: The members of a structure do not occupy memory until they are
associated with a structure_variable. 9
• Example
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
struct student st;
• Multiple variables of struct student type can be declared
as:
struct student st1, st2, st3;
10
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Defining a structure…
• Each variable of structure has its own copy of member
variables.
• The member variables are accessed using the dot (.) operator or
memberoperator.
• For example: st1.name is member variable name of st1
structure variable while st3.gender is member variable gender
of st3 structure variable.
11
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Defining a structure…
struct student struct
{ {
char name[20]; char name[20]; int
int roll_no; roll_no; float marks;
float marks; char gender;
char gender; long intphone_no;
long intphone_no; }st1, st2, st3;
}st1, st2, st3;

12
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Structure initialization
• Syntax:
struct structure_name structure_variable={value1, value2, …, valueN};

• Note: C does not allow the initialization of


individual structure members within the
structure definition template.

13
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
void main()
{
struct student st1={“ABC", 4, 79.5, 'M', 5010670};
clrscr();
printf("Name\t\t\tRoll No.\tMarks\t\tGender\tPhone No.");
printf("\n.........................................................................\n");
printf("\n %s\t\t %d\t\t %f\t%c\t %ld", st1.name, st1.roll_no, st1.marks,
st1.gender, st1.phone_no);
getch();
}

14
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Partial Initialization
• We can initialize the first few members and leave the
remaining blank.
• However, the uninitialized members should be only at
the end of the list.
• The uninitialized members are assigned default
values as follows:
– Zero for integer and floating point numbers.
– ‘\0’ for characters andstrings.
15
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
void main()
{
struct student s1={“name", 4};
clrscr();
printf("Name=%s", s1.name);
printf("\n Roll=%d", s1.roll);
printf("\n Remarks=%c", s1.remarks);
printf("\n Marks=%f", s1.marks);
getch();
}

16
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Accessing member of structure/ Processing a structure


• By using dot (.) operator or period operator or member
operator.
• Syntax:
structure_variable.member
• Here, structure_variable refers to the name of a struct type
variable and member refers to the name of a member
within thestructure.
17
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Question
• Create a structure named student that has name, roll and
mark as members. Assume appropriate types and size of
member. Write a program using structure to read and display
the data entered by the user.

18
struct student
{
char name[20];
int roll;
float mark;
};

void main()
{
struct student s;
clrscr();
printf("Enter name:\t");
gets(s.name);
printf("\n Enter roll:\t");
scanf("%d", &s.roll);
printf("\n Enter marks:\t");
scanf("%f", &s.mark);
printf("\n Name \t Roll \t Mark\n");
printf("\n...................................\n");
printf("\n%s\t%d\t%f", s.name, s.roll, s.mark);
getch();
}
19
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Copying and Comparing Structure Variables


• Two variables of the same structure type can be copied in the same way as ordinary
variables.
• If student1 and student2 belong tothe same structure, then the following statements
are valid:
student1=student2; student2=student1;
• However, the statements such as:
student1==student2 student1!=student2
are not permitted.
• If we need to compare the structure variables, we may do so by comparing members
individually.
20
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI. Here, structure has beendeclared
global i.e. outside of main()
function. Now, any function can
access it and create a structure
variable.
structstudent printf("\nStudent2.name=%s",
{ student2.name);
char name[20];
printf("\nStudent2.roll=%d",
int roll;
student2.roll);
};
void main() if(strcmp(student1.name,student2.na
{ me)==0 &&
struct student student1={“ABC", 4, }; (student1.roll==student2.roll))
struct student student2; {
clrscr(); printf("\n\n student1 and student2
student2=student1; aresame.");
}
getch();
16
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

How structure elements are stored?


• The elements of a structure are always stored in contiguous
memory locations.
• A structure variable reserves number of bytes equal to sum of
bytes needed to each of its members.
• Computer stores structures using the concept of “word boundary”.
In a computer with two bytes word boundary, the structure
variables are stored left aligned and consecutively one after the
other (with at most one byte unoccupied in between them called
slackbyte).

22
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

How structure elements are stored?


• When we declare structure variables, each
one of them may contain slack bytes and the
values stored in such slack bytes are
undefined.
• Due to this, even if the members of two
variables are equal, their structures do not
necessarily compare.
• That’s why C does not permit comparison of
structures.
23
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Array of structure
• Let us consider we have a structure as:
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
• If we want to keep record of 100 students, we have to make 100
structure variables like st1, st2, …,st100.
• In this situation we can use array of structure to store the records of
100 students which is easier and efficient to handle (because loops
can be used).
24
Array of structure…

• Two ways to declare an array


of structure: struct student
• struct student {
•{ char name[20];
int roll;
• char name[20]; int
char remarks;
roll;
float marks;
• char remarks; float };
marks; struct student st[100];
• }st[100];

25
• Write a program that takes roll_no,fname lname of 5
students and prints the same records in ascending order
on the basis of roll_no
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Reading values
for(i=0; i<5; i++)
{
printf("\n Enter roll number:"); scanf("%d",
&s[i].roll_no);

printf("\n Enter first name:"); scanf("%s",


&s[i].f_name);

printf("\n Enter Lastname:"); scanf("%s",


&s[i].l_name);
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Sorting values
for(i=0; i<5; i++)
{
for(j=i+1; j<5; j++)
{
if(s[i].roll_no<s[j].roll_no)
{
temp = s[i].roll_no;
s[i].roll_no=s[j].roll_no;
s[j].roll_no=temp;
}
}
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Question
• Define a structure of employee having data members
name, address, age and salary. Take the data for n
employees in an array and find the average salary.
• Write a program to read the name, address, and
salary of 5 employees using array of structure.
Display information of each employee in alphabetical
order of theirname.
29
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Array within Structure


• We can use single or multi dimensional arrays of
type int or float.
• E.g. struct student
{
char name[20];
int roll;
float marks[6];
};
struct student s[100]; 30
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

• Here, the member marks contains six


elements, marks[0], marks[1], …, marks[5]
indicating marks obtained in six different
subjects.
• These elements can be accessed using
appropriate subscripts.
• For example, s[25].marks[3] refers to the
marks obtained in the fourth subject by the
26th student.

Array within structure… 31


SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

for(i=0;i<n;i++)
Reading Values
{
printf("\n Enter information about student%d",i+1); printf("\n
Name:\t");
scanf(" %s", s[i].name); printf("\n
Class:\t"); scanf("%d", &s[i]._class);
printf("\n Section:"); scanf(" %c",
&s[i].section);
printf("\n Input marks of 6subjects:\t"); for(j=0;j<6;j++)
{
scanf("%f", &temp);
s[i].marks[j]=temp;
} } 27
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Structure within anotherStructure (Nested Structure)


• Let us consider a structure personal_record to store the
information of a personas:
• struct personal_record
{
char name[20]; int day_of_birth;
int month_of_birth; int year_of_birth;
float salary;
}person; 33
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Structure within anotherStructure (Nested Structure)…


• In the structure above, we can group all the items related to birthday together and declare
them under a substructure as:
struct Date
{
int day_of_birth; int month_of_birth; int
year_of_birth;
};
struct personal_record
{
char name[20]; struct Date birthday; float
salary;
}person;
34
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Structure within anotherStructure (Nested Structure)…


• Here, the structure personal_record contains a member named birthday
which itself is a structure with 3 members. This is called structure within
structure.
• The members contained within the inner structure canbe accessed as:
person.birthday.day_of_birth
person.birthday.month_of_birth person.birthday.
year_of_birth
• The other members within the structure personal_record are accessed as
usual:
person.name person.salary 35
printf("Enter name:\t");
scanf("%s", person.name);
printf("\nEnter day of birthday:\t");
scanf("%d", &person.birthday.day_of_birth);
printf("\nEnter month of birthday:\t");
scanf("%d", &person.birthday.month_of_birth);
printf("\nEnter year of birthday:\t");
scanf("%d", &person.birthday.year_of_birth);
printf("\nEnter salary:\t");
scanf("%f", &person.salary);

36
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Structure within anotherStructure (Nested Structure)…


• Note:- More than one type of structures can
be nested…

37
struct date
{
int day;
int month;
int year;
};

struct name
{
char first_name[10];
char middle_name[10];
char last_name[10];
};

struct personal_record
{
float salary;
struct date birthday,deathday;
struct name full_name;
};

38
• Create a structure named date that has day, month and year as
its members. Include this structure as a member in another
structure named employee which has name, id and salary as
other members. Use this structure to read and display
employee’s name, id, date of birthday andsalary.

39
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Pointer to Structure
• A structure type pointer variable can be declared as:
struct book
{
char name[20];
int pages; float price;
};
struct book *bptr;
• However, this declaration for a pointer to structure does not allocate any memory for a structure but allocates
only for a pointer, so that to access structure’s members through pointer bptr, we must allocate the memory
using malloc()function.
• Now, individual structure members are accessed as:
bptr->name bptr->pages bptr->price

(*bptr).name (*bptr).pages (*bptr).price


• Here, -> is called arrow operator and there must be a pointer to the structure on the left side of this operator.
40
struct book *bptr;

bptr=(struct book *)malloc(sizeof(structbook));

printf("\n Enter name:\t");


scanf("%s", bptr->name);
printf("\n Enter no. of pages:\t");
scanf("%d", &bptr->pages);
printf("\n Enter price:\t");
scanf("%f", & bptr->price=temp)

41
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Pointer to Structure…
• Also, the address of a structure type variable can be stored in a structure type
pointer variableas follows:
struct book
{
char name[20]; int pages;
float price;
};
struct book b,*bptr; bptr=&b;
• Here, the base address of b is assigned tobptr pointer.
42
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Pointer to Structure…
• Now the members of the structure book can
be accessed in 3 ways as:
b.name bptr->name (*bptr).name
b.pages bptr->pages (*bptr).pages
b. price bptr-> price (*bptr).price

43
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Pointer to array of structure


• Let we have a structure asfollows:
struct book
{
char name[20]; int pages;
float price;
};
struct book b[10],*bptr;
• Then the assignment statement bptr=b; assigns the address of
the zeroth element of b to bptr.
44
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Pointer to array of structure…
• The members of b[0] can be accessedas:
bptr->name bptr->pages bptr->price
• Similarly members of b[1] can be accessedas:
(bptr+1)->name (bptr+1)->pages (bptr+1)->price
• The following for statement can be used to print all the values of
array of structure b as:
for(bptr=b;bptr<b+10;bptr++)
printf(“% s % d % f”, bptr->name, bptr->pages, bptr-
>price); 45
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Problem
• Define a structure of employee having data members name,
address, age and salary. Take data for n employee in an array
dynamically and find the averagesalary.
• Define a structure of student having data members name,
address, marks in Clanguage, and marks in information system.
Take data for n students in an array dynamically and find the
total marksobtained.
46
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Function and Structure


• We will consider four caseshere:
– Passing the individual members to functions
– Passing whole structure to functions
– Passing structure pointer to functions
– Passing array of structure to functions

47
Passing structure member to functions

• Structure members can be passed to functions


as actual arguments in function call like
ordinary variables.
• Problem: Huge number of structure members
• Example: Let us consider a structure employee
having members name, id and salary and pass
these members to afunction:

48
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

display(emp.name,emp.id,emp.salary);

Void display(char e[],int id ,float sal)


{
printf("\ nName\ t\ tID\ t\ tSalary\ n);
printf("%s\t%d\t%.2f",e,id,sal);
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Passing whole structure to functions


• Whole structure can be passed to a function by the syntax:
• function_name(structure_variable_name);
• The called function has the form:
• return_type function_name(struct tag_namestructure_variable_name)
• {
• … … … … …;
• }

45
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

display(emp);

void display(struct employee e)


{
printf("\nName\tID\tSalary\n");
printf("%s\t%d\t%.2f",e.name,e.id,e.salar);
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Passing structure pointer tofunctions


• In this case, address of structure variable is passed as an actual
argument to a function.
• The corresponding formal argument must be a structure type
pointer variable.
• Note: Any changes made to the members in the called function
are directly reflected in the calling function.
47
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

display(&emp);

void display(struct employee *e)


{
printf("\nName\tID\tSalary\n");
printf("%s\t%d\t%.2f",e->name,e->id,e->salary);
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Passing array of structures to function


• Passing an array of structure type to a function is similar to
passing an array of any type to afunction.
• That is, the name of the array of structure is passed by the
calling function which is the base address of the array of
structure.
• Note: The function prototype comes after the structure
definition.
49
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

display(emp); //emp is array name of size 2


void display(struct employee ee[])
{
int i;
printf("\n Name\t\t ID\t\t Salary\n");
for(i=0;i<2;i++)
{
printf("%s\t\t%d\t\t%.2f\n",ee[i].name,ee[i].id,ee[i].salary);
}
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Structure using typedef


• It allows us to introduce synonyms for data types which could have been
declared some other way.
• It is used to give New name to the Structure.
• New name is used for Creating instances, Passing values to
function,declaration etc…
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Example:
#include<stdio.h>
int main()
{
typedef int Number;
Number num1 = 40,num2 = 20;
Number answer;
answer = num1 + num2;
printf("Answer : %d",answer);
return(0);
}
Output :
Answer : 60
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

• In the above program we have used typedef to create alias name to


data type. We have created alias name to ‘int’ data type. We have
given new name to integer data type i.e ‘Number’.

• In the second example, Record is tag-name. ’employee’ is nothing


but New Data Type. We can now create the variables of
type ’employee’ Tag name is optional.
Different Ways of Declaring
Structure using Typedef :
typedef struct typedef struct Record
{
char ename[30];
{
int ssn; char ename[30];
int deptno; int ssn;
} int deptno;
employee;
}
employee;
Live Example : Using Typedef For
Declaring Structure
#include<stdio.h> {
typedef struct b1 printf("\nName of Book :s",b1.bname);
{ printf("\nSSN of Book : %d",b1.ssn);
char bname[30]; printf("\nPages in Book : %d",b1.pages);
int ssn; return(0);
int pages; }
} OUTPUT:
book; Name of Book : Let Us C
book b1 = {"Let Us
C",1000,90}; SSN of Book : 1000
int main() Pages in Book : 90
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Pointer to Structure Array


• Like we have array of integers, array of pointers etc, we can also have
array of structure variables. And to use the array of structure variables
efficiently,
• we use pointers of structure type. We can also have pointer to a single
structure variable, but it is mostly used when we are dealing with array
of structure variables.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Accessing Structure Members with Pointer


#include <stdio.h>
struct Book
{ char name[10];
int price; }
int main()
{
struct Book a; //Single structure variable struct Book* ptr; //Pointer of Structure type ptr = &a;
struct Book b[10]; //Array of structure variables struct Book* p; //Pointer of Structure type
p = &b;
return 0;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Accessing Structure Members with Pointer


• To access members of structure using the structure variable, we used the
dot . operator.

• But when we have a pointer of structure type, we use arrow -> to access
structure members.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Accessing Structure Members with Pointer


#include <stdio.h>
struct my_structure {
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {"StudyTonight", 35, 1}; struct my_structure *ptr; ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Bit Manipulation
• Suppose we want to store the gender of the person , then instead of wasting the
complete byte we can manipulate single bit. We can consider Single bit as a flag.
Gender of Person can be stored as [M/F] . By Setting the flag bit
• 1 we can set Gender as “Male” and “Female” by setting bit as 0
• 1. To pack Several data objects in the single memory word , Bits are used.
• 2. Flags can be used in order to store the Boolean values ( T / F ).
• 3. A method to define a structure of packed information is known as bit fields.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Syntax : Bit Manipulation


struct databits
{
int b1 : 1;
int b2 : 1;
int b3 : 1;
int b4 : 4;
int b5 : 9;
}data1;
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Explanation :
• In the above example, we can say that we have allocated specific number of
bits to each structure member.

• Integer can store 2 bytes (*) , so 2 bytes are manipulated in bits and 1 bit is
reserved for b1. Similarly b2,b3 will get single bit.

• Similarly we can structure efficiently to store boolean values or smaller


values that requires little membory.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

How to access the Individual Bits ?

• data1.b1
• data1.b2
• data1.b3
• data1.b4
• data1.b5
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

How to initialize Structure ?


struct databits
{
--
---
}data1 = { 1,1,0,10,234 };
Initialized Result –

data1.b1 = 1
data1.b2 = 1
data1.b3 = 0
data1.b4 = 10
data1.b5 = 234
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Unions
• Unions are quite similar to the structures in C.
• Union is also a derived type as structure.
• Union can be defined in same manner as structures just the keyword
used in defining union in union where keyword used in defining
structure was struct.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

union car
syntax
{

char name[50];

int price;

};

Union variables can be created in similar manner as structure variable.

union car

char name[50];

int price;

}c1, c2, *c3;

OR

union car

char name[50];
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Accessing members of an union

• The member of unions can be accessed in similar manner as that structure.


Suppose, we you want to access price for union variable c1 in above example,
it can be accessed as c1.price. If you want to access price for union pointer
variable c3, it can be accessed as (*c3).price or as c3->price.
Example
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
#include <stdio.h>
union job
{
char name[32];
float salary;
int worker_no;
}u;
struct job1
{
char name[32];
float salary;
int worker_no;
}s;
int main()
{
output
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

size of union = 32
size of structure = 40
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Memory allocation
There is difference in memory allocation between union and structure as suggested in below example. The amount
of memory required to store a structure variables is the sum of memory size of all members.

But, the memory required to store a union variable is the memory required for largest element of an union.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Diff between structure and union


• All members of structure can be accessed at any time. But, only one
member of union can be accessed at a time in case of union and
other members will contain garbage value.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Example
#include <stdio.h>
union job
{
char name[32];
float salary;
int worker_no;
}u;
int main()
{
printf("Enter name:\n");
scanf("%s",u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

output
Enter name Hillary
Enter salary 1234.23
Displaying Name: f%Bary
Salary: 1234.2
Initially, Hillary will be stored in u.name and other members of union
will contain garbage value. But when user enters value of salary,
1234.23 will be stored in u.salary and other members will contain
garbage value. Thus in output, salary is printed accurately but, name
displays some random string.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Accessing Union Members
• To access any member of a union, we use the member access operator (.).
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

output
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got
corrupted because the final value assigned to the variable has
occupied the memory location and this is the reason that the value
of str member is getting printed very well.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Example
• Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having unions

#include <stdio.h>
#include <string.h>
union Data
{ int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

data.i : 10
output
data.f : 220.500000
data.str : C Programming
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Dynamic Arrays
• Dynamic arrays are created using pointer variables and memory
management functions malloc,calloc and realloc.

• The concept of dynamic arrays is used in creating and manipulating data


structures such as linked list, stacks and queues.
File Handling in C
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

What is a File?
• A file is a collection of related data that a computers treats as a single
unit.
• Computers store files to secondary storage so that the contents of
files remain intact when a computer shuts down.
• When a computer reads a file, it copies the file from the storage
device to memory; when it writes to a file, it transfers data from
memory to the storage device.
• C uses a structure called FILE (defined in stdio.h) to store the
attributes of a file.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Steps in Processing a File


1. Create the stream via a pointer variable using the FILE structure:
FILE *p;
2. Open the file, associating the stream name with the file name.
3. Read or write the data.
4. Close the file.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

The basic file operations are


• fopen - open a file- specify how its opened (read/write) and type
(binary/text)
• fclose - close an opened file
• fread - read from a file
• fwrite - write to a file
• fseek/fsetpos - move a file pointer to somewhere in a file.
• ftell/fgetpos - tell you where the file pointer is located.
File Open Modes
More on File Open Modes
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Additionally,
• r+ - open for reading and writing, start at beginning
• w+ - open for reading and writing (overwrite file)
• a+ - open for reading and writing (append if file exists)
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

File Open
• The file open function (fopen) serves two purposes:
• It makes the connection between the physical file and the stream.
• It creates “a program file structure to store the information” C needs to
process the file.
• Syntax:
filepointer=fopen(“filename”, “mode”);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

More On fopen
• The file mode tells C how the program will use the file.
• The filename indicates the system name and location for the
file.
• We assign the return value of fopen to our pointer variable:
spData = fopen(“MYFILE.TXT”, “w”);
spData = fopen(“A:\\MYFILE.TXT”, “w”);
More On fopen
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Closing a File
• When we finish with a mode, we need to close the file before ending
the program or beginning another mode with that same file.
• To close a file, we use fclose and the pointer variable:
fclose(spData);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
fprintf()
Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
fscanf()
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
getc()
Syntax:
identifier = getc (file pointer);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = getc (fp);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

putc()
write a single character to the output file, pointed to by
fp.
Example:
FILE *fp;
char ch;
putc (ch,fp);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

End of File
• There are a number of ways to test for the end-of-file
condition. Another way is to use the value returned by the
fscanf function:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Reading and Writing Files


#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f \n ", a, b, c) ;
printf (“ %f %d %f \n ", e, f, g) ;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

#include <stdio.h> Example


#include<conio.h>
void main()
{
char ch;
FILE *fp;
fp=fopen("out.txt","r");
while(!feof(fp))
{
ch=getc(fp);
printf("\n%c",ch);
}
getch();
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

fread ()
Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

Remarks:
fread reads a specified number of equal-sized
data items from an input stream into a block.

ptr = Points to a block into which data is read


size = Length of each item read, in bytes
n = Number of items read
stream = file pointer
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Example Example:
#include <stdio.h>
int main()
{
FILE *f;
char buffer[11];
if (f = fopen("fred.txt", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:\n%s\n", buffer);
}
return 0;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

fwrite()
Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);

Remarks:
fwrite appends a specified number of equal-sized data items to an output file.

ptr = Pointer to any object; the data written begins at ptr


size = Length of each item of data
n =Number of data items to be appended
stream = file pointer
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Example
Example:
#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

fseek()
This function sets the file position indicator for the stream pointed to by stream or you can say it seeks a specified place
within a file and modify it.

SEEK_SET Seeks from beginning of file


SEEK_CUR Seeks from current position
SEEK_END Seeks from end of file

Example:
#include <stdio.h>
int main()
{
FILE * f;
f = fopen("myfile.txt", "w");
fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END
fputs(" India", f);
fclose(f);
return 0;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

ftell()
offset = ftell( file pointer );

"ftell" returns the current position for input or output on the file
#include <stdio.h>

int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

THANK YOU………

You might also like