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

PSC 2020 Lecture Notes Unit 5

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

PSC 2020 Lecture Notes Unit 5

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

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.

The general syntax of structure is given below:

struct <tagname>
{
datatype membername1;
datatype membername2;
};

Where tagname, membername1, membername2 should be an identifier and data type


can be either fundamental or derived data type.

Declaration and Initialization:

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:

Above main function Within main function

struct student main()


{ {
char name[20],course[5]; struct student
int rollno; {
}s1={“ARYA”,”BTECH”,123}; char name[20],course[5];
int rollno;
Or } s1={“ARYA”,”BTECH”,123};
}
struct student
{ Or
char name[20],course[5];
int rollno; main()
}s1; {
struct student s1={“ARYA”,”BTECH”,123}; struct student
main() {
{ char name[20],course[5];
} int rollno;
} s1;
Explanation: struct student s1={“ARYA”,”BTECH”,123};
In the above example student is the structure }
name and s1 is the structure variable Explanation:
declared In the above example student is the structure
and the values are initialized to the structure Name and s1 is the structure variable declared
variable within flower braces and the values are initialized to the structure an
variable within flower braces

Accessing members of the Structure:


The member’s of the structure can be accessed with a variable declared of that structure type
and with dot operator(.)

The general form is shown below:

structure variable name.member name

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.

Nested Structures or structure within structure:


Structure defined within another structure is said to be nested structures. Below are given
examples of the different ways of making a structure nested.

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:

The concept of array of structures is illustrated below:

struct student
{
int rollno;
int marks1;
};

struct student s1[3];


In the above example s1 is a variable declared as array of structures, where s1 is the variable
name and the value 3 enclosed in square brackets gives the size of the array variable.

Accessing the member of the structure with array of structure variable

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

Arrays within structures


Concept of Array within a structure is illustrated below:
struct student
{
int rollno;
int marks[3];
};
struct student s1;

in the above example variable marks is declared as array of type int.

Accessing the members of the structure

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.

Passing Structures to Functions:


Structures and Functions:
Structure variable can be passed as argument to function in two ways that is by value and by
reference. Below we will see with example the procedure of passing structure variable as
arguments by value and by reference.

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.

Declaring a Structure Pointer


Like other pointers, structure pointers are declared by placing * in front of a structure
variable's name. For example, assuming the previously defined structure addr, the following
declares addr_pointer as a pointer to data of that type:
struct addr *addr_pointer;

Using Structure Pointers


There are two primary uses for structure pointers:
 to pass a structure to a function using call by reference
 to create linked lists and other dynamic data structures that rely on dynamic
allocation.

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;

Union-Definition and Declaration:


Union follow the same syntax as structures. Unions and structures. Union and structures
differ in terms of storage. In structures, each member has its own storage location, whereas
all the members of a union use the same location. This implies that, aithough a union may
contain many members of different types, it can handle only one member at a time.
Like structures, a union can be declared using the keyword union as follow:
union item
{
Int m;
Float x;
Char c;
}code;

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

Memory storage of union


The compiler allocates a piece of storage that is large enough to hold the largest variable type
in the union. As shown in the example declaration, the member x requires 4 bytes which is
the largest among the members, It is assumed that a float variable requires 4 bytes of storage
and the figure above shows how all the three variables share the same address.

ACCESING A UNION MEMBER:

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.

The general form of a bit-field definition is

data type name : length;

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:

Bit Meaning When Set

0 Change in clear-to-send line


1 Change in data-set-ready
2 Trailing edge detected
3 Change in receive line
4 Clear-to-send
5 Data-set-ready
6 Telephone ringing
7 Received signal

Typedef:
The keyword typedef allows us to define an existing data type with other name. The general
form of typedef is given below:

typedef datatype newname;

For e.g.,
typedef int integer;

typedef float real;

In the above example, int is redefined as integer and float redefined as real.

Below we will see a simple example of how typedef is used.


#include <stdio.h>
main()
{
typedef int integer;
typedef float real
integer rollno;
real per_marks;
printf(“enter value rollno and per_marks:”);
scanf(“%d %f”,&rollno,&per_marks);
}

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

File System Basics :

Steps for file operations:


There are three steps for file operation in C. They are
1. Opening the file
2. Reading or writing the data from or into the file
3. Closing the file.

Opening the file:


A file should be opened to perform any operation of reading or writing or closing a file. A file
can be opened by using the fopen() function as shown below:
File pointer=fopen(file name, mode);

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.

Fread and Fwrite:


Reading the contents of the file:
Once the file is opened in read mode, its contents can be read by using any of the functions
listed below:

Function Purpose Usage


Name

fgetc() Reads the character from the Variable=fgetc(file pointer);


current position of the file Where variable should be declared as of type
pointer and advances the file char and file pointer should be declared as of
pointer to point to the next type FILE and the file pointer should
character beassigned to fopen() function opened in the
mode r or r+.
getc() Reads the character from the Variable=getc(file pointer);
current position of the file Where variable should be declared as of type
pointer and advances the file char and file pointer should be declared as of
pointer to point to type FILE and the file pointer should be
the next character assigned to fopen() function opened in the
mode r or r+.
fscanf() Reads all types of data from fscanf(file pointer,”control string”,variable
the file list);
Where file pointer should be declared as of
type FILE and the file pointer should be
assigned to fopen() function opened in the
mode r or r+ and the control string specifies
the format of how the contents of a file to be
read and variable list are variables declared
for its type and
matches with the format specifiers in the
control string.
fgets() Reads the contents of the fgets(variable,size,filepointer);
file as string. Where variable should be declared as
character array of some size and size specifies
the number of characters to be read from the
file and file pointer should be declared as of
type FILE and the file pointer should
be assigned to fopen() function opened in the
mode r or r+.
getw() Reads an integer from the Variable=getw(file pointer);
File Where variable should be declared as of type
int and file pointer should be declared as of
type FILE and the file pointer should be
assigned to
fopen() function opened in the mode r or r+.
fread() Reads an entire block form fread(&structure variable,size of (structure
the file variable),1,file pointer);

/* sample program to read data from file as characters */


#include <stdio.h>
main()
{ char ch;
file *fp; /* fp declared as file pointer */
fp=fopen(“sample.dat”,”r”); /* fp is assigned with fopen function with sample.dat file
opened in read mode */
if (fp==NULL) /* checking whether the file exists or not */
printf(“error reading file\n”);
else
while((ch=fgetc(fp))!=EOF) /* reads the character from the file using fgetc until EOF is
reached */
printf(“%c”,ch);
fclose(fp);
}

Writing the contents to the file:


Once the file is opened in write or append mode, data can be written to the file by using any
of the functions listed below:

Function name Purpose Usage


fputc() writes the character to fputc(variable,file pointer);
the Where variable should be declared
current position of the as of type char and file pointer
file should be declared as of type FILE
pointer and advances and the file pointer should be
the file assigned to fopen() function
pointer to point to the opened in any one the mode
next w,w+,a or
character a+.
putc() writes the character to putc(variable,file pointer);
the
current position of the Where variable should be declared
file as of type char and file pointer
pointer and advances should be declared as of type FILE
the file and the file pointer should be
pointer to point to the assigned to fopen() function
next opened in any one of the mode
character w,w+,a
or a+.
fprintf() Writes all types of data fprintf(file pointer,”control
to the string”,variable list);
File Where file pointer should be
declared as of type FILE and the file
pointer should be assigned to
fopen() function opened in any one
of
the mode w,w+,a or a+ and the
control string specifies the format
of
how the contents of a file to be
written and variable list are
variables
declared for its type and matches
with the format specifiers in the
control string.
fputs() Writes the contents of fputs(variable,filepointer);
the file Where variable should be declared
as string. as character array of some size
and file pointer should be declared
as of type FILE and the file
pointer should be assigned to
fopen() function opened in the
mode
w,w+,a or a+.
putw() Writes an integer into putw(variable,file pointer);
the file Where variable should be declared
as of type int and file pointer
should be declared as of type FILE
and the file pointer should be
assigned to fopen() function
opened in the mode w,w+,a or a+.
fwrite() Writes an entire block fwrite(&structure variable,size of
into the (structure variable),1,file pointer);
File
/* sample program to write data into file as characters */
#include <stdio.h>
main()
{ char ch;
file *fp; /* fp declared as file pointer */
fp=fopen(“samp.dat”,”w”); /* fp is assigned with fopen function with samp.dat file opened
in write mode */
while((ch=getchar())!=’0’) /* reads the character from the file using fgetc until EOF is
reached */
fputc(ch,fp);
fclose(fp);
}

Closing the file:

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.

Error handling while reading/writing files:

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”);

Checking whether the file pointer has reached end of file:

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”);

Checking whether the file has been successfully opened:

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”):

printing the error messages of the compile:

The perror function is used to print the error messages of the compiler

Random Access with Files:

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:

fseek(file pointer, offset, position);

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

1 SEEK_CUR Current position of the file pointer

2 SEEK_END End of the file

Below are also listed few examples of the fseek function.


statement Meaning
fseek(fp,m,1) Move the file pointer forward by m bytes from the current
position
fseek(fp,-m,1) Move the file pointer backward by m bytes from the current
postion.
fseek(fp,-m,2) Move the file pointer backward by m bytes from the end 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:

rewind (file pointer):

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

COMMAND LINE ARGUMENTS


 All C programs define a function main() that designates the entry point of
the program and is invoked by the environment in which the program is
executed.
 int main(int argc, char *argv[])
 This declaration states that
 main returns an integer value (used to determine if the program
terminates successfully).
 argc is the number of command-line arguments including the
command itself, i.e., argc must be at least 1.
 argv is an array of the command-line arguments.
 Equivalent form:
 int main(int argc, char **argv)
 When the program starts, the following conditions hold true.
 argc is greater than 0.
 argv[argc] is a null pointer.
 argv[0], argv[1], ..., argv[argc–1] are pointers to strings with
implementation-defi ned meanings.
 argv[0] is a string that contains the program’s name . The remaining
members of argv are the program’s arguments.

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.

You might also like