Unit - 4 (Structures)
Unit - 4 (Structures)
1
• The basic data types in C are int, float and char. using
these data types, we can derive some other data types,
the data types that are derived from the basic data
types are called derived data types.
• Structure definition
• initialization and accessing the members of a
structure
• nested structures
• structures and functions
• self- referential structures
• unions and enumerated data types.
STRUCTURES
Structure Definition
A structure is a collection of one or more variables,
possibly of different data types, grouped together
and stored under a single name .
How to define a structure
Defined in three different ways
1. Tagged Structure
2. Structure Variables
3. Typedef Structure
1. Tagged Structure
struct tag_name
{
type1 member1;
type2 member2;
……………
……………
};
Where,
struct is the keyword which tells the compiler that a structure is being
defined.
Tag_name is the name of the structure.
member1, member2 … are called members of the structure.
The members are declared within curly braces.
The closing brace must end with the semicolon.
Example: student details using tagged structure
Tag name
keyword
struct student
{
char rno[10];
Curly braces char name[30]; Members of structure
surround or
The structure float marks; structure elements
elements };
Semi colon required
Memory is not reserved for the structure definition since no variables are
associated with the structure definition. The members of the structure do not occupy
any memory until they are associated with the structure variables
The declaration of the structure variable takes of the form
The following figure shows the memory organization for the above example .
s1
------ rno ------> <- name -> <- Marks ->
< 10 Bytes > < 30 Bytes > < 4 Bytes >
Where,
struct is the keyword which tells the compiler that a structure is being defined.
tag_name is the name of the structure.
member1, member2 … are called members of the structure.
The members are declared within curly braces.
var1, var2… are structure variables that follow curly braces.
Here each variable occupies memory.
The closing brace must end with the semicolon
• Example struct student
{
char rno[10];
char name [30];
float marks;
} s1;
struct student
{
char rno[10];
char name [30];
float marks;
} s1,s2;
We can omit the tag name from the structure definition, the following is valid.
struct
{
char rno[10];
char name [30];
float marks;
} s1;
Does Not Reserve Space Reserves Space
A type definition, typedef, gives a name to a data type by creating a new type
that can then be used anywhere a type is permitted.
11
Type-definition Format
The general syntax of the typedef is as follows,
where typedef is the keyword that tells the compiler about the type
definition, data_type refers to an existing data type and IDENTIFIER
refers the “new” name given to the data type.
Note that using typedef, we are not creating new data types.
Instead we are creating only new name for the existing data type.
These new data type names are called user-defined data types.
12
Suppose we want to store marks scored in various subjects
in variables sub1, sub2 and sub3. These variables can be
declared as follows,
13
//Example program to demonstrate typedef
14
3. Typedefined Structure
The structure definition associated with keyword typedef is called
type-defined structure.
This is the most powerful way of defining the structure.
The typedef
syntax ofstruct
typedefined structure is
{
type1 member1;
type2 member2;
……
} TYPE_ID;
where,
typedef is keyword added to the beginning of the definition.
struct is the keyword which tells the compiler that a structure is being de
member1, member2…are called members of the structure.
The closing brace must end with type definition name which in turn
ends with semicolon.
• Example: Student details
//Structure Definition
typedef struct
{
char rno[10];
char name [30];
float marks;
} STUDENT; //no memory is allocated for
structure
/* structure declaration */
STUDENT s1, s2; //memory is allocated for the variables.
Note: Using typedef it is not possible to declare a variable.
But, we can have user defined data type. TYPE_ID can be
treated as the new data type.
INITIALIZATION OF STRUCTURES
Structure initialization also similar to the array initialization.
Initializing values are put into curly braces and values separated
by commas.
Struct student s1={var1,var2,…..varn};
6 1 \0 r a m u \0 7 5 . 5
2. Initialize during structure variable declaration
struct student
{
char rno[10];
char name[30];
float mark;
};
struct student s1={“61”,”ramu”,75.5};
points to remember
1. members of the structure cannot be initialized in the structure definition.
struct student
{
char rno[10]=“61”;
invalid
char name[30];
float marks;
}s1;
2. We can initialize one structure variable at a time. The values are
assigned to members in the order specified in the structure
declaration.
3. During partial initialization, the values are assigned to members in
the order specified and remaining members are initialized with
garbage value.
ex- struct student s1={“61”};
will assign the string 61 to rno and remaining members are initialized
to garbage value.
however the statement
s1= {“ramu”,75.5}; invalid
HOW TO ACCESS STRUCTURE MEMBERS
• Structures use a dot (.) operator to refer its elements, also known as
period operator.
• structure_variable_name. structure_member_name.
• Before dot, there must always be a structure variable. After the dot,
there must always be a structure member
1000
2000
Example on structures using pointers.
Struct student
{
int rno;
char name[10];
float avg;
};
void main()
{
struct student s1;
struct student *ptr;
ptr=&s1;
printf(“\n enter student details”);
scanf(“%d %s %f”, &ptr->rno,ptr->name,&ptr-
>avg);
printf(“\n rollno=%d”,ptr->rno);
printf(“\n name=%s”,ptr->name);
printf(“\n average=%f”,ptr->avg);
SELF REFERENTIAL STRUCTURE
• A structure declaration which includes at least one member as a pointer to the same
structure is known as self-referential structure.
• Can be linked together to form useful data structures such as lists, queues, stacks and
trees.
• Terminated with a NULL pointer (0).
• The syntax for using the self referential structure as follows,
Struct tag_Name
Example
{
struct student
type1 member1;
{
type2 member2;
int rno;
….
struct student *next;
Struct tag_Name *next;
}s1,s2;
};
ARRAYS WITH IN STRUCTURES
• It is also possible to declare an array as a member of structure, like
declaring ordinary variables.
• For example to store marks of a student in three subjects the we
can have the following definition of a structure.
• struct student
{
char name [5];
int roll_number;
int marks [3];
float avg;
};
• Then the initialization of the array marks done as follows,
• struct student s1= {“ravi”, 34, {60,70,80},70.0};
• The values of the member marks array are referred as follows,
• s1.marks [0] --> will refer the 0th element in the marks
• s1.marks [1] --> will refer the 1st element in the marks
• s1.marks [2] --> will refer the 2ndt element in the marks
• This program illustrates how to read values into the structure and access the
members of the structure. Struct student
{
char name[30];
char rollno[10];
float marks[3];
};
void main() {
struct student s1;
int i;
printf(“\n enter student details”);
scanf(“%s”,s1.name);
scanf(“%s”,s1.rollno);
for(i=0;i<3;i++)
scanf(“%f”,&s1.marks[i]);
printf(“\n display student details”);
printf(“\n%s”,s1.name):
printf(“\n%s”,s1.rollno);
for(i=0;i<3;i++)
printf(“ %f”,s1.marks[i]);
}//main
ARRAY OF STRUCTURES
• As we have an array of integers, we can have an array of structures
also. For example, suppose we want to store the information of all
the students of a class, consisting of name, roll_number and marks,
A better approach would be to use an array of structures.
• Array of structures can be declared as follows,
•
struct tag_name arrayName[size];
Let’s take an example, to store the information of 3 students,
we can have the following structure definition and declaration,
struct student
{
char name[10];
int rno;
float avg;
};
struct student s[3];
Defines array called s, which contains three elements.
Each element is defined to be of type struct student
• For the student details, array of structures can be initialized as follows,
• struct student s[3]={{“ABC”,1,56.7},{“xyz”,2,65.8},{“pqr”,3,82.4}};
• The memory organization of the variables is illustrated in the below Figure,
…..
…. …. …
…. … … …
EXAMPLE ON ARRAY OF STRUCTURES
struct student
{
char name[30];
printf(“\n display student details”);
char rollno[10];
for(i=0;i<3;i++)
float marks;
{
};
printf(“\n student %d”,i+1);
void main()
printf(“\n name=“);
{
puts(s[i].name);
struct student s[3];
printf(“roll no=“);
int i;
puts(s[i].name);
printf(“\nenter the student details”);
printf(“marks=“);
for(i=0;i<3;i++)
puts(s[i].marks);
{
}//for
gets(s[i].name);
}//main
gets(s[i].rollno);
scanf(“%f”,&s[i].marks);
}//for
NESTED STRUCTURES
• A structure which includes another structure is called nested
structure i.e a structure can be used as a member of another
structure.
• The syntax for the nesting of the structure as follows
struct tag_name1 Example
{ struct student
{
type1 member1; char name [10];
……. int roll_number;
……. int marks [3];
struct tag_name2 float avg;
{ struct data
type1 member1; {
…… int day;
…… int month;
} var1; int year;
}var2; } dob;
}s1;
• The syntax for accessing members of a nested structure as follows,
outer_structure_variable.innerstructurevariable.membername
Example
struct student
{ s1.dob.day;
char name [10]; s1.dob.month;
int roll_number; s1.dob.year;
int marks [3]; s1.name;
float avg; s1.roll_number;
struct data
{
int day;
int month;
int year;
} dob;
}s1;
• Another way of using nested structures are
struct data
struct tag_name1
{
{
int day;
type1 member1;
int month;
…….
int year;
…….
};
};
struct student
struct tag_name2
{
{
char name [10];
type1 member1;
int roll_number;
……
struct data dob;
……
int marks [3];
struct tag_name1 var;
float avg;
……
} s1;
};
Note that the above structure consists of a member identified by dob whose type is
struct data.
The members contained in the inner structure namely day, month and year can be
referred to as
s1.dob.day s1.dob.month s1.dob.year
EXERCISE
• Write a c program to define a structure student having members roll no, name,
class, section,marks. Create an array of 10 students give the data and find the
average marks, in section wise.
//Program to demonstrate structure with functions.
#include<stdio.h>
struct student
{
int rollno;
char name[20];
}s1;
c i f
a.c
a.i
a.f
Enumerated Types
43
Declaring an Enumerated Type:
enum tag_name
{
member1;
member2;
…. Anther way of declaring the variables are shown below:
…. enum tag_Name var;
}var1,var2,var3;
44
Following are some of the examples of enumerator type:
enum color
enum days
{
{
RED,
SUNDAY,
BLUE,
MONDAY,
GREEN
…
};
SATURDAY
enum color c1, c2;
} d1;
By default the first member of the enum type is given the value 0.
- The next values are initialized to adding one to the previous value.
Second member value is 1 and so on.
RED-0,BLUE-1,GREEN-2
45
We can override it and assign our own values.
For example, to make JAN start with 1 we could use the following
declaration.
enum month
{
JAN=1, FEB, MAR, APR, MAY,JUN, JUL, AUG, SEP, OCT, NOV, DEC
}m1;
46
//Example program to demonstrate enum
#include<stdio.h>
main()
{
enum color
{
RED,
GREEN,
BLUE
}c1;
printf("%d %d %d",RED,GREEN,BLUE); Output:
c1 = BLUE; 0 1 2
printf("\n%d ",c1); 2
}
47
48
49
Arrays Structures Unions
Keyword … struct union
Definition An array is a A structure is a collection A union is a collection of
homogeneous of logically related logically related elements,
collection of data. elements, possibly of possibly of different types,
different types, having a having a single name, shares
single name. single memory location.
Declaration data_type struct tag_name union tag_name
array_Name[size]; { {
type1 member1; type1 member1;
type1 member2; type1 member2;
…………… ……………
…………… ……………
}; };
struct tag_name var; union tag_name var;
51
FILES
Every operating system uses a set of rules for naming its files.
The file name may contain two parts, a primary name and an optional
period with extension.
Example: input.txt
program.c
55
55
FILE INFORMATION TABLE:
56
56
BUFFER/ STREAM
60
60
STREAM FILE PROCESSING:
When the file is opened, the stream and the file are associated with
each other.
62
62
FILE OPERATIONS
• Several operations are applied on the files.
1. creation a file
2. opening an existing file
3. reading from a file
4. closing a file.
5. writing to a file.
6. copying a file.
7. moving to a desired location in a file.
1.CREATION OF A FILE
• File name as “abc.c” and write some data in the file and save
in your folder then it permanently stored on to the disk.
• Abc.c
2. OPEN A FILE
Before read or write data from or to a file on a disk we must open the file
using the function fopen() .
it takes two arguments
1. file name which is to be opened
2. mode of a file whether it is read or write
fopen() performs three tasks
1. searches file on a disk which is to be opened
2. loads the file from disk to memory called buffer (temporary memory)
3. sets a character pointer that points to the first character of the buffer.
What is the need of buffer at all?
When we want to read a character from the file every time we need to access
the disk it takes the more time for the disk drive to position the read/write
head correctly.
- Read the file character by character from the buffer is efficient rather than
from disk.
• To open a file, we need to specify the physical filename and its mode.
• Syntax
fopen (“filename”,
• fopen() returns the address “mode”);
of the first character of the buffer which is
collected in the structure pointer called fp.
• Hence we declared as
FILE *fp;
FILE structure is defined in the header file “stdio.h”.
FILE OPENING MODES
while creating a file we are also specifying the purpose of opening this file.
The modes does this job.
1. “r” (read mode)- searches for the file. If file exist on disk, brought
into the memory and sets the pointer points to the first character in
the memory. If file does not exist returns the NULL.
syntax fopen(“filename”,”r”);
operation- reading the file.
2. “w” (write mode) - searches for the file. if file exist overwrite its
contents. If not create a new file . If space is not available on the
disk returns the NULL.
syntax fopen(“filename”,”w”);
operation- writing to a file.
3. “a” ( append mode) - searches file. If file already exist it returns the
pointer points to last character in the file. The new data is added at
the end of the file.
If the file doesn’t exist, it is created and opened. In this case, the
writing will start at the beginning of the file.
syntax fopen(“filename”,”a”);
operation- adding new contents to the end of the file.
4. “r+” ( read and write mode) - same as r mode. If file does not exist it
returns NULL.
Syntax: fopen (“filename”,”r+”);
operations are different – reading, writing new contents and modifying
the existing contents of the file.
5. “w+”-(write and read) writing new contents, reading them back and
modifying the existing contents of the file. If a file already exists its
contents erased. If a file does not exist then new file created.
Syntax: fopen (“filename”,”w+”);
6. “a+” (append and read) - reading existing contents, appending new
contents at the end of the file and cannot modify the existing content of
the file.
syntax: fopen(“filename”,”a+);
File Modes
69
PROGRAM FOR CHECK
WHETHER THE FILE IS EXIST
OR NOT
void main()
{
FILE *fp;
fp=fopen(“abc.r”,”r”);
if(fp= =NULL)
{
puts(“ file does not exist\n”);
exit();
}//if
}//main
4. CLOSING A FILE
C includes many standard functions to input data from the keyword and
output data to the monitor.
72
72
73
73
FORMATED I/O FUNCTIONS:
We have already familiar with two formatting functions scanf and
printf.
These two functions can be used only with the keyboard and
monitor.
74
74
Reading from Files: fscanf ()
It is used to read data from a user-specified stream.(files)
The fscanf function would read values from the file "pointed"
to by fptr1 and assign those values
75
to a and b. 75
Writing to Files: fprintf ()
It can handle a group of mixed data simultaneously.
77
77
WRITES RECORD OF A STUDENTS
TO A FILE USING STRUCTURE
#include<stdio.h>
struct student
{
char name[30];
int rollno;
float marks;
};
void main()
{
FILE *fp;
struct student s;
fp=fopen("abc.c","w");
printf("\n enter name rollno and marks of a student\n");
scanf("%s %d %f",s.name,&s.rollno,&s.marks);
fprintf(fp,”%s\nr %d\n%f\n",s.name,s.rollno,s.marks);
fclose(fp);
}//main
READING RECORDS FROM A FILE
fscanf()- used to read the structure from a file
general form- fscanf(fp,”control string”,&var1,&var2….);
#include<stdio.h>
struct student
{
char name[30];
int rollno;
float marks;
};
void main()
{
FILE *fp;
struct student s;
fp=fopen("abc.c","r");
while(fscanf(fp,"%s %d %f",s.name,&s.rollno,&s.marks)!=EOF)
printf("%s\n %d\n%f\n",s.name,s.rollno,s.marks);
fclose(fp);
CHARACTER I/O FUNCTIONS:
Character input functions read one character at a time from a text
stream.
Character output functions write one character at the time to a text
stream.
Its return value is integer. Up on successful writing returns the ASCII value
of character. Otherwise returns EOF.
81 81
TERMINAL AND FILE CHARACTER I/O :
The getc functions read the next character from the stream,
which can be a user-defined stream or stdin, and converts it in
to an integer.
Syntax:
int getc (FILE *spIn); or int getc(stdin);
int fgetc (FILE *spIn); or int fgetc(stdin);
83
83
Write a Character: putc () and fputc ()
The putc function writes a character to the stream which can
be a user-defined stream, stdout, or stderr.
readf.c
• #include<stdio.h>
void main()
{
FILE *fp;
Char c;
fp=fopen(“readf.c”,”r”);
while((c=fgetc(fp))!=EOF)•While loop would be exit when it reaches to
the EOF which is special character of
printf(“%c”,c);
ascii value 26 placed beyond the last
fclose(fp); character of the file, when the file is created.
}//main
•EOF is macro defined in the file stdio.h
WRITING CHARACTERS ON TO A FILE
In the text format, data are organized into lines, terminated by newline character.
The text files are in human readable form and they can be created and read using any
text editor.
Text files are read and written using input / output functions that convert characters
to data types: scanf and printf, getchar and putchar, fgets and fputs.
92
Reading and Writing Text Files 92
Binary File:
A binary file is a collection of data stored in the internal format of
the computer.
Binary files are read and written using binary streams known as block
input / output functions.
93
Block Input and Output 93
Differences between Text File and Binary File
94
Mode Meaning
This mode opens a binary file in write mode.
wb
Example: fp=fopen (“data.dat”,”wb”);
This mode opens a binary file in read mode.
rb
Example: fp=fopen (“data.dat”,”rb”);
This mode opens a binary file in append mode.
ab
Example: fp=fopen (“data.dat”,”ab”);
This mode opens/creates a binary file in write and read mode.
w+b
Example: fp=fopen (“data.dat”,”w+b”);
This mode opens a pre-existing binary file in read and write mode.
r+b
Example: fp=fopen (“data.dat”,”r+b”);
This mode opens/creates a binary file in append mode.
a+b
Example: fp=fopen (“data.dat”,”a+b”);
C language uses the block input and output functions to read and write
data of binary files.
As we know that data are stored in memory in the form of 0’s and 1’s.
When we read and write the binary files, the data are transferred
just as they are found in memory and hence there are no format
conversions.
The block read function is file read(fread) and the block write
function is file write (fwrite).
96
96
• To write the records on to a binary file use library function fwrite()
• fwrite() takes 4 arguments
syntax
To read the records from a file use fread with four arguments .
fread (&structure variable,sizeof(structure variable),no.of records to be
read at a time,file pointer);
/* write a c program to write and read a student record by using fwrite() and fread()*/
#include<stdio.h>
Struct student{
Char name[30];
int rollno;
float marks;
}s;
void main(){
FILE *fptr;
fptr=fopen(“student.dat”,”wb+”);
scanf(“%s %d %f”,s.name,&s.rollno,&s.marks);
fwrite(&s,sizeof(s),1,fptr);
fread(&s,sizeof(s),1,fptr);
fclose(fptr);}//main
COMMAND LINE ARGUMENTS
FILE *fp;
Char ch;
FILE *fp1,*fp2;
How to execute this command line arguments
program
fp1= fopen(argv[i],”r”);
fp2= fopen(argv[2],”w”);
if(fp1)
To compile cc filename.c
{
putc(ch,fp2);
}//if
else
fclose(fp1);
fclose{fp2);
}//main
• /* write c c program to create a file by command line argument and add
text given by the user to that file and open the file created above and display it
#include<stdio.h>
void main(int argc,char *argv[])
{
char ch;
FILE *fp;
fp=fopen(argv[1],"w");
while((ch=getchar())!=EOF)
fputc(ch,fp);
fclose(fp);
fp=fopen(“xyz.c”,”r”);
while((ch=fgetc(fp))!=EOF)
printf(“%c”,ch);
fclose(fp);
}//main
RANDOM ACCESS TO FILES
void main()
char ch;
fptr=fopen("fseekExout.c","w+");
while((ch=getchar())!=EOF)
fputc(ch,fptr);
printf("\n");
rewind(fptr);
fseek(fptr,n,0);
fseek(fptr,10L,1);
fclose(fptr);
}//main