0% found this document useful (0 votes)
1 views

Module-5

This document is a module on structures, unions, and enumerated data types in C programming, detailing the definition, declaration, initialization, and usage of structures. It explains how to create user-defined data types, access their members, and perform operations such as copying and comparing structures. Additionally, it covers the size of structures and how to pass them to functions in C.

Uploaded by

naxibew907
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Module-5

This document is a module on structures, unions, and enumerated data types in C programming, detailing the definition, declaration, initialization, and usage of structures. It explains how to create user-defined data types, access their members, and perform operations such as copying and comparing structures. Additionally, it covers the size of structures and how to pass them to functions in C.

Uploaded by

naxibew907
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

1

Dr. H N National College of Engineering, Bengaluru


Department of Computer Science and Engineering
Principles of Programming Using C
Module-5
By,
Dr. Vikhyath K B

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


Module-5 Structure, Union and
Enumerated Data Type
2

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.

• A structure is, therefore, a collection of variables under a single name. The


variables within a structure are of different data types and each has a name that is
used to select it from the structure.

15.1.1 Structure Declaration


• A structure is declared using the keyword struct followed by the structure name. All
the variables of the structure are declared within the structure. A structure type is
generally declared by using the following syntax:

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


3

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.

struct student stud1;

• Here, struct student is a data type and stud1 is a variable.

• Another way of declaring variables: The variable declaration at the time of


structure declaration.
struct student
{
int r_no;
char name[20];
float fees; Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
}stud1, stud2;
5

• 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


6

Example:

• Declare a structure to store information about a point in the coordinate system.

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.

• By using typedef, no new data is created, rather an alternate name is given to a


known data type.

• Syntax: typedef existing data_type new data_type;

• Note: typedef statement does not occupy any memory, it simply defines a new
type.

• Example: typedef int INTEGER;

• 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.

• A typedef declaration is a synonym for the type.

typedef struct student


{
int r_no;
char name[20];
float fees;
};

• 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;

15.1.3 Initialization of Structure


• A structure can be initialized in the same way as other data types are initialized.
Initializing a structure means assigning some constants to the members of the
structure.

• 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).

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


10

• 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.

Syntax to initialize a structure variable is:

struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;

}struct_var = {constant1, constant2, constant3, …};

OR

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


11

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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.1.4 Accessing the Members of a
Structure
13

• Each member of a structure can be used just like a normal variable, but its name
will be a bit longer.

• A structure member variable is generally accessed using a ‘.’ (dot) operator.

• Syntax: struct_var.member_name

• The dot operator is used to select a particular member of the structure.

• 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;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


14

• The input values for data members of the structure variable stud1, we may write:

• scanf(“%d”, &stud1.r_no);
• scanf(“%s”, stud1.name);

• Similarlly, to print the values of structure variable stud1, we may write:

• printf(“%s”, stud1.course);
• printf(“%f”, &stud1.fees);

• Memory is allocated when we declare variables of the structure. In the absence of


any variable, structure definition is just a template that will be used to reserve
memory when a variable of type struct is declared.

• 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:

• struct student stud1 = {01, “Rahul”, “BCA”, 45000};


• struct student stud2;

• Then to assign one structure variable to another we will write:


• stud2 = stud1;

• 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


16

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


17

• 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.

• Example: To compare the fees of two students, we will write:

if(stud1.fees > stud2.fees)

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.1.6 Finding the size of a structure
18

• 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

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


20

Using sizeof operator: This operator is used to calculate the size of a data
type, variable, or an expression.

• To use this operator simply write, sizeof (struct_name);

• 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

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


22

Subtracting the Addresses: In this technique, we use an array of structure


variables. Then we subtract the address of first element of next consecutive variable
from the address of the first element of preceding structure variable.

Example: The code below finds the size of structure Employee.


#include<stdio.h>
typedef struct Employee
{
int emp_ID;
char name[20];
double salary;
char designation[20];
float experience;
};
int main()
{
struct Employee e[5];
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
int start, end, len;
23

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

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.4 Structures and functions
24

• There is a mechanism to pass structures to functions and return them. A function


may access the members of a structure in three ways:

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.4.1 Passing Individual Members
25

• 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;

void display(int, int);

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


26

int main()
{
POINT p1 = {2, 3};
display(p1.x, p1.y);
return 0;
}

void display(int a, int b)


{
printf(" The coordinates of the point are:%d %d", a, b);
}

Output:
The coordinates of the point are: 2 3

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.4.2 Passing the Entire Structure
27

• 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:

struct struct_name func_name(struct struct_name struct_var);

#include<stdio.h>
typedef struct
{
int x;
int y;
}POINT;
void display(POINT);

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


28

int main()
{
POINT p1 = {2, 3};
display(p1);
return 0;
}
void display(POINT P)
{
printf(“%d %d”, p1.x, p1.y);
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.4.3 Passing Structure Through
Pointers
29

¨ Passing large structures to functions using the call-by-value method is very


inefficient.

¨ It is preferred to pass structures through pointers. It is possible to create a pointer to


almost any type in C, including user-defined types.

¨ It is extremely common to create pointers to structures. As in other cases, a pointer


to a structure is never itself a structure, but merely a variable that holds the address
of a structure.
¨ Syntax:
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
}*ptr;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
30

OR
struct struct_name *ptr;

¨ For student structure, we can declare a pointer variable by writing

struct student *ptr_stud, stud;


¨ The next thing to do is to assign the address of stud to the pointer using the address
operator (&) as we would do in case of any other pointer. So, to assign a address:

ptr_stud = &stud;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.6 Unions
31

¨ Similar to structures, a union is a collection of variables of different data types. The


only difference between a structure and a union is that in case of unions, we can
only store information in one field at any one time.

¨ To better understanding a union, think of it as a chunk of memory that is used to


store variables of different types. When a new value is assigned to a field, the
existing data is replaced with the new data.

¨ 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.6.1 Declaring a Union
32

¨ 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.6.2 Accessing a Member of a Union
33

¨ 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.

15.6.3 Initializing Unions


¨ A striking difference between a structure and a union is that in case of a union, the
fields share the same memory space, so fresh data replaces any existing data.
#include <stdio.h>
typedef struct POINT1
{
int x, y;
};

typedef union POINT2


{
int x;
int y; Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
};
34

int main()
{
struct POINT1 P1 = {2, 3};

// POINT2 P2 = {4, 5}; Illegal with union

union POINT2 P2;


P2.x = 4;
P2.y = 5;
printf("\n The co-ordinates of P1 are %d and %d", P1.x, P1.y);
printf("\n The co-ordinates of P2 are %d and %d", P2.x, P2.y);
return 0;
}

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++)

printf("\n Co-ordinates of Point[%d] are %d and %d",i,points[i].x,points[i].y);


return 0;
}

Output:

Co-ordinates of Point[0] are 3 and 3


Co-ordinates of Point[1] are 5 and 5
Co-ordinates of Point[2] are 7 and 7

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.8 Unions Inside Structures
37

¨ Unions are useful when declared inside a structure.


¨ Example: Here we want to field of a structure to contain a string or an integer,
depending on what the user specifies.

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

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


38

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

printf("\n Enter the marks:");


scanf("%d", &stud.marks);
if(choice=='y' || choice =='Y')
printf("\n Name: %s", stud.name);
else
printf("\n Roll Number: %d", stud.roll_no);
printf("\n Marks: %d", stud.marks);
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.9 Structures Inside Unions
40

¨ 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.10 Enumerated Data Type
41

¨ 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};

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


42

¨ 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

¨ RED = 0, BLUE = 1, BLACK = 2, GREEN = 3, YELLOW = 4, PURPLE = 5,


WHITE = 6

¨ If we want to explicitly assign values to these integer constants then you should
specifically mention those values shown as follows:

¨ enum COLORS {RED = 2, BLUE, BLACK = 5, GREEN = 7, YELLOW,


PURPLE, WHITEK =B,15}
Dr. Vikhyath Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25
43

¨ As a result of this statement, now RED = 2, BLUE = 3, BLACK = 5, GREEN = 7,


YELLOW = 8, PURPLE = 9, WHITE = 15.
#include <stdio.h>
int main()
{
enum { RED = 2, BLUE, BLACK = 5, GREEN = 7, YELLOW, PURPLE, WHITE=15};
printf("\n RED = %d", RED);
Output:
printf("\n BLUE = %d", BLUE);
printf("\n BLACK = %d", BLACK); ¨ RED = 2

printf("\n GREEN = %d", GREEN); ¨ BLUE = 3


printf("\n YELLOW = %d", YELLOW);
¨ BLACK = 5
printf("\n PURPLE = %d", PURPLE);
printf("\n WHITE = %d", WHITE); ¨ GREEN = 7

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

¨ As we know enumerated constants are basically integers, so programs with


statements such as int fore_color = RED; is considered to be a legal statement in C.
¨ In extension to this, C also permits the user to declare variables of an enumerated
data type in the same way as we create variables of other basic data types.
Syntax:
¨ enumeration_name variable_nam;
¨ So to create a variable of COLORS, we may write
¨ enum COLORS bg_color;

¨ 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;

¨ Then, we can straightaway declare variables by writing

¨ color forecolor = RED;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


15.10.3 Assigning values to Enumerated
Variables
46

¨ 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.

¨ enum COLORS bg_color, border_color;


¨ bg_color = BLACK;
¨ border_color = bg_color;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


16. Files
47

¨ A file is a collection of data stored on a secondary storage device like hard disk.

¨ Broadly speaking, a file is basically used because real-life applications involve


large amounts of data and in such applications the console-oriented I/O operations
pose two major problems:

¨ First, it becomes cumbersome and time-consuming to handle huge amount of data


through terminals.

¨ 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:

¨ Standard input: (stdin)


¨ Standard output: (stdout)
¨ Standard error: (stderr)

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


49

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


161.2 Buffer Association with File
Systems
50

¨ 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


51

¨ 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


16.1.3 Types of Files
52

¨ 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


53

¨ 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.

16.2 Using Files in C

To use files in C, we must follow the steps as below:


¨ Declare a file pointer variable
¨ Open the file
¨ Process the file
¨ Close the file

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


16.2.1 Declaring a File Pointer Variable
54

¨ 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;

For example, if we write


FILE *fp;
Then, fp is declared as a file pointer.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


16.2.2 Opening a file
55

¨ 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 *fopen(const char *file_name, const char *mode);

¨ 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


56

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


57

¨ Code given below helps to open a file using fopen().

FILE *fp;
fp = fopen(“Student.DAT”, “r”);
if(fp == NULL)
{
printf(“\n The file could not be opened”);
exit(1);
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


58

The fopen() function can fail to open the specified file under certain conditions that are
listing as follows:

¨ Opening a file that is not ready for use


¨ Opening a file that is specified to be on a non-existent directory/drive
¨ Opening a non-existent file for reading
¨ Opening a file to which access is not permitted

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


16.2.3 Closing a File Using fclose()
59

¨ 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.

¨ The prototype of the fclose() function can be given as:

¨ int fclose(FILE *fp)

¨ Here, fp is a file pointer which points to the file that has to be closed.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


60

¨ 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).

¨ The prototype of fcloseall() can be given as:

int fcloseall(void);

¨ fcloseall() also flushes any stream buffers and returns the number of streams
closed.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


16.3 reading Data From Files
61

¨ C provides the following set of functions to read data from a file.

¨ 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, …);

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


62

¨ 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:

¨ char *fgets(char *str, int size, FILE *stream);

¨ 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


16.3.3 fgetc()
63

¨ The fgetc() function returns the next character from stream, EOF if the end of file
is reached, or if there is an error.

¨ Syntax:

¨ int fgetc(FILE *stream);

¨ fgetc() returns the character read as an int or returns EOF to indicate an error or
end of file.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


16.3.4 fread()
64

¨ The fread() function is used to read data from a file.

Syntax:

¨ int fread(void *str, size_t size, size_t num, FILE *stream);

¨ The fread() function reads num number of objects and places them into the array
pointed to by str.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25


65 Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 13/01/25

You might also like