PSC 2020 Lecture Notes Unit 5
PSC 2020 Lecture Notes Unit 5
Structures
Structure is a very useful derived data type supported in C that allows grouping one or more
Variables of different data types with a single name.
struct <tagname>
{
datatype membername1;
datatype membername2;
};
Structure can be declared and initialized either above the main function or within the
main function. The process of defining, declaring and initializing of structure is illustrated
below:
For eg.,
struct student
{
char name[20],course[5];
int rollno;
}s1; // s1 is a variable declared of type struct student
main()
{
printf(“enter the name,course and rollno:”);
scanf(“%s%s%d”,s1.name,s1.course,&s1.rollno);
printf(“name=%s\n”,s1.name);
printf(“course=%s\n”,s1.course);
printf(“rollno=%d\n”,s1.rollno);
}
Explanation:
In the above example a structure by name student is declared with members name and
course declared as character array and rollno declared of typed as int. The scanf statement
shows how data is read for the members of the structure through structure variable likewise
the printf statement shows how to print the data of the members of the structure.
struct employee
{
int empid;
char designation[15];
struct salary
{int basic;
int da;
}s1;
}emp;
struct date
{
int day;
int month;
int year;
};
struct employee
{
int empno;
char name[20];
float basic;
struct date joindate;
}emp1;
Arrays of Structures:
struct student
{
int rollno;
int marks1;
};
The following segment of code illustrates the process of accessing the structure with array of
structure variables.
for(i=0;i<3;i++)
{
scanf( “%d”,&s1[i].rollno);
scanf(“%d”,&s1[i].marks1);
}
Here s1 is the structure variable declared as an array,rollno and marks1 are members of the
The following segment of code illustrates the process of accessing arrays within structure.
for(i=0;i<3;i++)
scanf(“%d”,&s1.marks[i]);
where s1 is the structure variable, marks is the member of structure declared as array variable
and I is subscript variable used to vary the index of the array variable. The members of the
structures declared as array are accessed by giving the structure variable name followed by
dot operator and then the member name with subscript variable enclosed in square
brackets.
By Value
struct employee
{
int empid;
char designation[15];
float salary;
}emp;
main()
{
readvalue(emp); /* function call with structure variable passed as argument */
}
readvalue(e)
struct employee e;
{
printf(“enter employee id, designation, salary:”);
scanf(“%d%s%f”,&e.empid,e.designation,&e.salaray);
}
Explanation:
In the above example the structure variable is passed as argument in the function call and
received in an argument by name e declared of the same structure in the called function and
the procedure of reading data to the member of the structure is the same as what we have
discussed
above.
By Reference
struct employee
{
int empid;
char designation[15];
float salary;
}emp;
main()
{
readvalue(&emp); /* function call with structure variable passed as argument */
}
readvalue(e)
struct employee *e;
{
printf(“enter employee id, designation, salary:”);
scanf(“%d%s%f”,&e->empid,e->designation,&e->salaray);
printf(“employee id =%d\n”,(*e).empid);
printf(“designation=%s\n”,(*e).designation);
printf(“salary=%f\n”,(*e).salary);
}
Explanation:
In the above example the structure variable is passed as reference argument in the function
call and received in an argument by name e declared of the same structure as pointer in the
called function.
The procedure of reading data to the member of the structure is done using
&pointervariable->membername for members declared of type int or float and if the
member is a string then the data is accessed using pointervariable->membername.
The procedure of printing data of the member of the structure is done using
(*pointervariable).membername
Structure Pointers:
C allows pointers to structures just as it allows pointers to any other type of object.
Unions:
A union is a memory location that is shared by two or more different types of variables. A
union provides a way of interpreting the same bit pattern in two or more different ways.
Declaring a union is similar to declaring a structure. Its general form is
union tag {
type member-name;
type member-name;
type member-name;
.
} union-variables;
This declaration declares a variable code of type union item. The union contains three
members, each with a different data type . However ,only one can be used at a time. This is
due to the fact that only one lacation is allocated for a union variable, irrespective of its size.
The following figure describes the memory arrangement of the union discussed above.
1000 1001 1002 1003
storage
bytes c
m
x
To access a union member, we can use the same syntax that we use for structure members.
For example, the statement such as
Code.m = 150;
Code.x = 785;
Printf(‘%d’, code.m);
Would produce an erroneous output (which is machine dependent). The user must keep track
of what type of information is stored at any given time.
Thus a union creates a storage location that can be used by any one of its members at a time.
When a different member is assigned a new value, the new value supersedes the previous
member’s value.
Unions may be used in all places where a structure is allowed. The notation for accessing
a union member which is nested inside a structure remains the same as for the nested
structures.
USES OF UNION:
Unions, like structures, contain members whose individual data types may differ from one
another. However, the members that compose a union share the same storage area within
the computer’s memory, whereas each member within a structure is assigned its own unique
storage area. Thus unions are used to conserve memory.
They are useful for applications involving multiple members, where values need not be
assigned to all the members at any one time. Unions are also used wherever the requirement
is to access the same memory locations in more than one way. This is often required while
calling basic input/output system functions (often simply called BIOS routines) present in the
read only memory (ROM) of the computer.
Many DOS-based application software’s need to access DOS’s internal data structures.
The break-up of these internal data structures, however, is not consistent and often changes
from one version of DOS to another. Therefore, to make the application programs compatible
with different versions of DOS, these programs create unions which take into account the
variations in the break-up of these DOS data structures. These programs when executed, first
test the version member of DOS being used on the machine and then access the appropriate
part of the union.
Structures Unions
Structures are derived data types that Unions are derived data types that allows to
allows togroup one or more variables of group one or more variables of different data
different datatype with a single name. type with single name.
Syntax: Syntax:
struct <tagname> union <tagname>
{ {
Data type member name; Data type member name;
Data type member name; Data type member name;
}; };
Example: Example:
struct college union type
{ {
int collegeid; int x;
char collegaddress[20]; char y;
}c; float z;
Here c is the structure variable declared }u;
which Here u is the union variable declared which
takes a size of 22 bytes i.e., 2 bytes for takes a size of 4 bytes i.e., 2 bytes for member
the x, 1 byte for member y and 4 bytes for member
member college id and 20 bytes for the z and the maximum of these is 4 bytes which
member will be the size allocated to the union variable.
collegeaddres
Size allocated to the union variable is the
Size allocated to the structure variable is maximum number of bytes allocated to any
thesum of the bytes allocated to the member of the structure.
members of the structure.
Self Referential Structures
Self Referential structures are those structures that have one or more pointers which point
to the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential in
nature.
Example:
filter_none
brightness_4
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure
‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.
Bit Fields:
C has a built-in feature, called a bit-field, that allows you to access a single bit. Bit-fields can
be useful for a number of reasons, such as:
• If storage is limited, you can store several Boolean (true/false) variables in one byte.
• Certain devices transmit status information encoded into one or more bits within a byte.
• Certain encryption routines need to access the bits within a byte.
Although these tasks can be performed using the bitwise operators, a bit-field can add more
structure (and possibly efficiency) to your code.
A bit-field must be a member of a structure or union. It defines how long, in bits, the field is
to be.
Here, type is the type of the bit-field, and length is the number of bits in the field. The type of
a bitfield must be int, signed, or unsigned. (C99 also allows a bit-field to be of type _Bool.)
Bit-fields are frequently used when analyzing input from a hardware device. For example, the
status port of a serial communications adapter might return a status byte organized like this:
Typedef:
The keyword typedef allows us to define an existing data type with other name. The general
form of typedef is given below:
For e.g.,
typedef int integer;
In the above example, int is redefined as integer and float redefined as real.
File:
File is a set of records that can be accessed through set of library functions.
Stream:
A stream is a logical device that receives input data from the file or an input device and acts
as a source of input to the program. It also acts as a destination to receive the data from the
program and write to output device or screen or printer.
File types:
Depending on the type of access, there are two types of files namely:
Sequential file
Random access file
Sequential file:
The records in this type of files are accessed sequentially one after the other. It is more time
consuming.
Random access file:
The records in this type of files are accessed randomly. It is less time consuming.
Depending on the format of data stored in files, there are two types of files namely:
Text file
Binary file
Text file:
Text file is a file in which data is stored as ASCII encrypted information. i.e., all
information is converted from binary to text.
Text files should be opened by using any one of these modes only
“r”, ”w” , ”a”, ”r+”, ”w+”, ”a+”.
Text files can be accessed sequentially or randomly.
Functions used to operate on text file are getw(), getc(), fscanf(), putw(), putc(),
fprintf()
Binary file:
Binary file is a file in which data is stored in binary form i.e., as stored in the
memory of the computer.
Binary file should be opened by using any one of these modes only
“rb”, “wb”, “ab”, “r+b”, “w+b”, “a+b”.
Binary files can be accessed sequentially.
Functions used to operate on binary file are fread(), fwrite()
Where file pointer should be a valid identifier that should be declared as pointer of the data
type FILE.
Filename should be a string i.e., specify the name of the file with extension enclosed in
double quotes
Mode specifies the purpose for which the file should be opened. The mode takes a character
or characters that should be enclosed in double quotes. The mode can take any one of the
values listed below:
MODE PURPOSE
“r” Open the text file in read mode, if the file exists then file pointerpoints to the first
character of the file otherwise returns NULL to the file pointer
“w” Open the text file in write mode, if file already exists then thecontents of that file
are erased otherwise a new file is created.
“a” Open the text file for appending data to it, if the file exists then new data can be
appended to the file otherwise a new file is created
“r+” Open the existing text file for both reading and writing. If the file does not exist
then NULL is assigned to the file pointer.
“w+” Open the text file in write mode, if file already exists then the contents of that file
are erased otherwise a new file is created. The file pointer returns NULL if there is
error opening the file. The advantage is that the file can be used for both reading
and writing.
“a+” Open the text file for appending data to it, if the file exists then new data can be
appended to the file otherwise a new file is created. The advantage is that the file
can be used for reading also.
“rb” Open the pre-existing binary file in read mode otherwise returns NULL to the file
pointer if the file does not exist.
“wb” Open the pre-existing binary file in write mode otherwise creates a new file if the
file does not exist.
“ab” Open the pre-existing binary file for appending data to it otherwise creates a new
file if the file does not exist.
“r+b” Open the existing binary file for both reading and writing otherwise returns NULL
to the file pointer if the file does not exist
“w+b” Open the binary file in write mode, if file already exists then the contents of that
file are erased otherwise a new file is created. The file pointer returns NULL if there
is error opening the file. The advantage is that the file can be used for both reading
and writing.
“a+b” Open the binary file for appending data to it, if the file exists then new data can be
appended to the file otherwise a new file is created. The advantage is that the file
can be used for reading also.
The file that is opened in any mode should be closed after the operation is over.
The file can be closed using the fclose() function as shown below:
fclose(file pointer);
the above statement closes only the file associated with that file pointer. If suppose there
are more than one files opened and you want to close all the files then it can be done by
using the fcloseall() function.
ferror()
The ferror function is used to find out error when file read/write operation is carried out. The
function returns a non-zero integer value if an error has occurred during the read/write
operation otherwise returns zero.
The ferror function should be used in a conditional statement as shown in the example given
below.The general form of the ferror function is shown below:
ferror(file pointer);
for e.g.,
if (ferror(fp)!=0)
printf(“error has occurred\n”);
feof()
The feof function is used to check whether the file pointer has reached the end of the file or
not. The function returns non-zero value if end of file is reached otherwise returns zero. The
feof function should be used in a conditional statement as shown in the example given below
The general form of the feof function is shown below:
feof(file pointer);
for e.g.,
if (feof(fp)!=0)
printf(“end of file reached\n”);
The fopen function is assigned to the file pointer, when the file pointer gets assigned with
NULL value if there is error opening the file. This can be checked as shown below:
If (fp==NULL)
printf(“error opening file:\n”):
The perror function is used to print the error messages of the compiler
Functions used for random access or other file functions used for navigating the File
Pointer:
The functions that we saw for reading and writing are useful for sequential access. But there
arises situations where we want to access only a part of the file then, in such situations we
can use the following functions.
• fseek()
• ftell()
• rewind()
fseek()
This function is used to move the file pointer by a specified number of bytes in the forward
direction or backward direction from a location. The fseek() function takes the form:
Where file pointer should be a variable declared of type FILE and the file pointer should
be assigned with fopen() function in some mode
-offset takes a negative or positive long integer number that specifies the number of bytes to
be moved in the backward or forward direction from a particular position
- position takes one of the integer values or constants that specify the location from where
the file pointer should move. Below is given a table showing the integer value and constant
specifying the location of the file pointer.
Location of the file pointer
Integer
value Constant
0 SEEK_SET Beginning of the file
ftell()
This function is used to tell the current position of the file pointer. The general form of ftell()
function is shown below:
Variable=ftell(file pointer);
Where variable is assigned the current position of the file pointer and this variable should be
declared of type long and the file pointer should be a variable declared of type FILE and should
be assigned to fopen() function opened in some mode.
rewind ()
This function is used to reset the file pointer to the beginning of the file irrespective of
wherever it is positioned. The general form of the rewind () function is shown below:
where the file pointer should be a variable declared of type FILE and should be assigned
to fopen() function opened in some mode.
/* sample program to illustrate the usage of functions fseek, ftell, rewind */
#include <stdio.h>
main()
{ char ch;
int pos;
file *fp; /* fp declared as file pointer */
fp=fopen(“samp.dat”,”r”); /* fp is assigned with fopen function with samp.dat file opened in
write mode */
fseek(fp,5L,0); /* moves the file pointer forward by 5 bytes from BOF */
pos=ftell(fp); /* returns the current position of the file pointer to the variable pos */
rewind(fp); /* resets the file pointer to the beginning of the file */
pos=ftell(fp); /* returns the current position of the file pointer to the variable pos */
fclose(fp);
}
Important Questions
1. Briefly discuss about array of structures with example.
2. Briefly discuss about array within structure with example.
3. What is self-referential structure? Discuss with an example.
4. Enumerate the differences between structures and unions.
5. Define a file. Briefly discuss the basic operations performed on files.
6. Discuss the different modes supported in files
7. Write a program in C to read data from file and write the same into another file.
8. What do you mean by command line arguments? Discuss.
9. Differentiate a text file from binary file.
10. Write a program in C to merge two files.
Assignment Questions
1. Enumerate the differences between structures and unions.
2. Define a file. Briefly discuss the basic operations performed on files.