Module-5
Module-5
15.1 Introduction
• A structure is a user-defined data type that can store related information (even of
different data types) together. The major difference between the structure and the
array is that an array contains related information of the same data type.
struct struct-name
{
data_type var-name;
data_type var-name;
…
};
Example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
Now, the structure has become a user-defined data-type.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
4
• Each variable name declared within a structure is called a member of the structure.
The structure declaration, however, does not allocate any memory or consume
storage space. It just gives a template that conveys to the C compiler how the
structure should be laid out in memory and gives details of the member names.
Like any other data type, memory is allocated for the structure when we declare a
variable of the structure.
• Here, we declare two variables stud1 and stud2 of the type student.
• When we declare variables of the structure, separate memory is allocated for each
variable.
Example:
struct point
{
int x, y; Note:
}; • The name of structure and
the name of a structure
• Declare a structure to store customer information. member should not be the
same. Moreover, structure
struct customer name and its variable
{ name should also be
int cust_id; different.
char name[20];
long int phone_num;
int DOB;
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
15.1.2 Typedef Declarations
7
• The typedef (derived from type definition) keyword enables the programmer to
create a new data type name from an existing data type.
• Note: typedef statement does not occupy any memory, it simply defines a new
type.
• INTEGER is the new name of data type int. To declare variables using the new data
type name, precede the variable name with the data type name(new). Therefore, to
define an integer variable, we may now write
INTEGER num=5;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
8
• When we precede a struct name with typedef keyword, then the struct becomes a
new type.
• It is used to make the construct shorter with more meaningful names for types
already defined by C or for types that we have declared.
• Here, we have preadded the structure’s name with the keyword typedef, student
becomes a new data type.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
9
• Therefore, now we can straightaway declare variables of this new data type as we
declare variables of type int, float, char, etc. To declare a variable of structure
student we will just write,
student stud1;
• When the user does not explicitly initialize the structure, then C automatically does
that. For int and float members the values are initialized to zero and character and
string members are initialized to ‘\0’ by default (in the absence of any initialization
done by the user).
• The initializers are enclosed in braces and are separated by commas. However, care
must be taken to see that the initializers match their corresponding types in the
structure definition.
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
…
}struct_var = {constant1, constant2, constant3, …};
OR
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
…
};
struct struct_name struct_var = {constant1, constant2, constant3, …};
Example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}stud1 = {01, “Rahul”, “BCA”, 45000};
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
12
• Below figure illustrates how the values will be assigned to the individual fields of
the structure.
• When all the members of a structure are not initialized, it is called partial
initialization. In case of partial initialization, first few members of the structure are
initialized and those that are uninitialized are assigned default values.
• Each member of a structure can be used just like a normal variable, but its name
will be a bit longer.
• Syntax: struct_var.member_name
• For example, to assign value to the individual data members of the structure
variable stud1, we may write:
styd1.r_no = 01;
stud1.name = “Rahul”;
stud1.course = “BE”;
stud1.fees = 100000;
• The input values for data members of the structure variable stud1, we may write:
• scanf(“%d”, &stud1.r_no);
• scanf(“%s”, stud1.name);
• printf(“%s”, stud1.course);
• printf(“%f”, &stud1.fees);
• Once the variables of a structure are defined, we can perform a few operations on
them. For example, we can use the assignment operator ‘=‘ to assign the values of
one variable to another.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
15.1.5 Copying and Comparing
15
Structures
• We can assign a structure to another structure of the same type.
• Example: If we have two structure variables stud1 and stud2 of type struct student
as below:
• This statement initializes the members of stud2 with the values of members of
stud1. Therefore, now the values of stud1 and stud2 can be given as shown as
below.
• C does not permit comparison of one structure variable with another. However,
individual members of one structure can be compared with individual members of
another structure.
• When we compare one structure member with another structure’s member, the
comparison will behave like any other ordinary variable comparison.
• There are three different ways through which we can find the number of bytes a
structure will occupy in the memory.
Simple Addition: In this technique, we will make a list of all data types and add
the memory required by each.
Example:
struct Employee
{
int emp_ID;
char name[20];
double salary;
char designation[20];
float experience;
};
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
19
• Now, Size = size of emp_ID + size of name + size of salary + size of designation +
size of experience
• Size of emp_ID = 2
• Size of name = 20 * size of character
• Size of salary = 8
• Size of designation = 20 * size of character
• Size of experience = 4
• Therefore, size =
• = 2+20*1+8+20*1+4
• =2+20+8+20+4
• =54 Bytes
Using sizeof operator: This operator is used to calculate the size of a data
type, variable, or an expression.
• Example: The code below prints the size of the structure Employee.
#include<stdio.h>
typedef struct Employee
{
int emp_ID;
char name[20];
double salary;
char designation[20];
float experience;
};
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
21
void main()
{
struct Employee e;
printf(“\n %d”, sizeof(e));
}
Output:
54
start = &e[o].emp_ID;
end = &e[1].emp_ID;
len = end – start;
Printf(“\n Size of the structure = %d”, len);
}
Output:
Size of the structure 54
• To pass any individual member of the structure to a function we must use the direct
selection operator to refer to the individual members for the actual parameters.
• The called program does not know if the two variables are ordinary variables or
structure members.
#include <stdio.h>
typedef struct
{
int x;
int y;
}POINT;
int main()
{
POINT p1 = {2, 3};
display(p1.x, p1.y);
return 0;
}
Output:
The coordinates of the point are: 2 3
• Like any other variable, we can pass an entire structure as a function argument.
When structure is passed as an argument, it is passed using the call by value
method, i.e., a copy of each member of the structure is made.
• Syntax:
#include<stdio.h>
typedef struct
{
int x;
int y;
}POINT;
void display(POINT);
int main()
{
POINT p1 = {2, 3};
display(p1);
return 0;
}
void display(POINT P)
{
printf(“%d %d”, p1.x, p1.y);
}
OR
struct struct_name *ptr;
ptr_stud = &stud;
¨ Thus unions are used to save memory. They are useful for applications that involve
multiple members, where values need to be assigned to all the members at any one
time.
¨ The syntax of declaring a union is the same as that of declaring a structure. The
only difference is that instead of using the keyword struct, the keyword union
would be used.
Syntax:
union union_name
{
data_type var-name;
data_type var-name;
…
};
¨ Again, the typedef keyword can be used to simplify the declaration of union
variables.
¨ A member of a union can be accessed using the same syntax as that of a structure.
To access the fields of a union, use the dot operator(.), i.e., the union variable name
followed by the dot operator followed by the member name.
int main()
{
struct POINT1 P1 = {2, 3};
Output:
The co-ordinates of P1 are 2 and 3
The co-ordinates of P2 are 4 and 5
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
15.7 Arrays of Union Variables
35
¨ Like structures we can also have an array of union variables. However, because of
the problem of new data overwriting existing data in the other fields, the program
may not display the accurate results.
#include <stdio.h>
union POINT
{
int x, y;
};
int main()
{
union POINT points[3];
points[0].x = 2;
points[0].y = 3;
points[1].x = 4;
points[1].y = 5;
points[2].x = 6;
points[2].y = 7;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
36
for(int i=0;i<3;i++)
Output:
#include <stdio.h>
struct student
{
union
{
char name[20];
int roll_no;
};
int marks;
};
int main()
{
struct student stud;
char choice;
printf("\n You can enter the name or roll number of the student ");
printf("\n Do you want to enter the name? (Y or N):");
gets(choice);
if(choice=='y'||choice == 'Y')
{
printf("\n Enter the name:");
gets(stud.name);
}
else
{
printf("\n Enter the roll number:");
scanf("%d", &stud.roll_no);
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
39
¨ C allows users to have a structure within a union. There are two structure variables
in the union. The size of union will be the size of the structure variable which is
larger of the two. During run-time, programmer will choose to enter name or roll
number of the student and the corresponding action will thus be taken.
¨ The enumerated data type is a user-defined type based on the standard integer type.
¨ An enumeration consists of a set of named integer constants. In other words, in an
enumerated type, each integer value is assigned as identifier.
¨ To define enumerated data type, we use the keyword enum, which is the
abbreviation for ENUMERATE.
¨ Enumeration create new data types to contain values that are not limited to the
values that fundamental data types may take.
Syntax:
enum enumeration_name { identifier1, idetifier2, … , identifier};
Example:
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
¨ In case if we do not assign any value to a constant, the default value for the first
one in the list-RED has the value of 0.
¨ The rest of the undefined constants have a value 1 more than its previous one. That
is, if you do not initialize the constant, then each one would have a unique value.
¨ The first would be zero and the rest would count upwards. So, in the example
¨ If we want to explicitly assign values to these integer constants then you should
specifically mention those values shown as follows:
return 0; ¨ YELLOW = 8
}
¨ PURPLE = 9
¨ WHITE = 15
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
15.10.1 enum Variables
44
¨ This declares the variable called bg_color, which is of the enumerated data type,
COLORS. Another way to declare a variable can be as illustrated in the following
statement.
¨ Enum COLORS { RED, BLUE, BLACK, GREEN, YELLLOW, PURPLE,
WHITE} bg_color, fore_color;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
15.10.2 Using the Typedef Keyword
45
¨ C also permits to use the typedef keyword for enumerated data types.
Example:
typedef enum COLORS color;
¨ Once the enumerated variable has been declared, values can be stored in it.
However, an enumerated variable can hold only declared values for the type.
¨ Example: To assign the colour black to the background colour, we will write
bg_color = BLACK;
¨ An important thing to note here is that once an enumerated variable has been
assigned a value, we can store its value in another variable of the same type.
¨ A file is a collection of data stored on a secondary storage device like hard disk.
¨ Second when doing I/O using terminal, the entire data is lost when either the
program is terminated or computer is turned off.
¨ In order to use files, we have to learn file input and output operations, i.e., how
data is read from or written to a file. Although file I/O operations are almost same
as terminal I/O, the only difference is that when doing file I/O, the user must
specify the name of the file from which data should be read/ written.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
16.1.1 Stream in C
48
¨ In C, the standard streams are termed as pre-connected input and output channels
between a text terminal and the program.
¨ Stream is a logical interface to the devices that are connected to the computer.
Stream is widely used as a logical interface to a file where a file can refer to a disk
file, the computer screen, keyboard, etc.
¨ Although files may differ in the form and capabilities, all streams are the same.
¨ The three standard streams language are as follows:
¨ When a stream linked to a disk file is created, a buffer is automatically created and
associated with the stream.
¨ A buffer is nothing but a block of memory that is used for temporary storage of
data that has to be read from or written to a file.
¨ Buffers are needed because disk drivers are block-oriented devices as they can
operate efficiently when data has to be read/written in blocks of certain size. An
ideal buffer size is hardware-dependent.
¨ The buffer acts as an interface between the stream and the disk hardware. When the
program has to write data to the stream, it is saved in the buffer till it is full. Then
the entire contents of the buffer are written to the disk as a block.
¨ When reading data from a disk file, the data is read as a block from the file and
written into the buffer.
¨ The program reads data from the buffer. The creation and operation of the
operation of the buffer is automatically handled by the operating system.
¨ In C, the types of files can be broadly classified into two categories – ASCII text
files and binary files.
ASCII Text Files: A text file is a stream of characters that can be sequentially
processed by a computer in forward direction. For this reason, a text file is usually
opened for only one kind of operation at any given time.
Binary Files: A binary file may contain any type of data, encoded in binary form for
computer storage and processing purposes. Like a text file, a binary file is a collection
of bytes .
In C, a byte and a character are equivalent. Therefore, a binary file is also referred to
as a character stream with the following two essential differences.
¨ A binary file does not require any special processing of the data and each byte of
data is transferred to or from the disk unprocessed.
¨ C places no restrictions on the file, and it may be read from, or written to, in any
manner the programmer wants.
¨ There can be a number of files on the disk. In order to access a particular file, you
must specify the name of the file that has to be used.
¨ This is accomplished by using a file pointer variable that points to a structure FILE
(defined in stdio.h). The pointer will then be used in all subsequent operations in
the file.
Syntax:
FILE *file_pointer_name;
¨ A file must first be opened before data can be read from it or written to it. In order
to open a file and associate it with a stream, the fopen() function is used. The
prototype of foepn() can be given as
¨ File Name:
¨ Every file on the disk has a name associated with it. The naming convention of a
file varies from one operating system to another.
¨ File Mode:
¨ The second argument in fopen() is the mode. Mode conveys to C type of
processing that will be done with the file. The different modes in which a file can
be opened for processing are given below.
FILE *fp;
fp = fopen(“Student.DAT”, “r”);
if(fp == NULL)
{
printf(“\n The file could not be opened”);
exit(1);
}
The fopen() function can fail to open the specified file under certain conditions that are
listing as follows:
¨ To close an open file, the fclose() function is used which disconnects a file pointer
from a file. After fclose() has disconnected the file pointer from the file, the pointer
can be used to access a different file or the same file but in a different mode.
¨ The fclose() function not only closes the file, but also flushes all the buffers that
are maintained for that file.
¨ Here, fp is a file pointer which points to the file that has to be closed.
¨ In addition to fclose(), there is a function fcloseall() which closes all the streams
that are currently opened except the standard streams ( such as stdin, stdout, and
stderr).
int fcloseall(void);
¨ fcloseall() also flushes any stream buffers and returns the number of streams
closed.
¨ fscanf()
¨ fgets()
¨ fgetc()
¨ fread()
16.3.1 fscanf()
¨ The fscanf() function is used to read formatted data from the stream.
Syntax:
¨ int fscanf(FILE *stream, const char *format, …);
¨ The fscanf() function is used to read data from the stream and store them according
to the parameter format into the locations pointed by the additional arguments.
16.3.2 fgets()
¨ The fgets() function stands for file get string. The fgets() function is used to get a
string from a stream.
¨ Syntax:
¨ The fgets() function reads at most one less than the number of characters specified
by size from the given stream and stores them in the string str.
¨ The fgetc() function returns the next character from stream, EOF if the end of file
is reached, or if there is an error.
¨ Syntax:
¨ fgetc() returns the character read as an int or returns EOF to indicate an error or
end of file.
Syntax:
¨ The fread() function reads num number of objects and places them into the array
pointed to by str.