PCE Unit – 5: Programming With C 251FY3-06
Structures and Unions
C supports a constructed data type known as structure, a mechanism for packing data of
different types. Structure is a user-defined data type in C language which allows us to
combine data of different types together. A structure is a convenient tool for handling a
group of logically related data items. Structure help to organize complex data in a more
meaningful way.
Defining a Structure
Unlike arrays, structures must be defined first for their format that may be used later to
declare structure variables. For example:
struct record
{
int rollno;
char name[20];
float per;
};
struct record student1, student2;
The keyword struct declares a structure to hold the details of three data fields, namely
rollno, name and per. These fields are called structure elements or members. Each
member may belong to a different type of data. record is the name of the structure and is
called the structure tag.
Student1 and student2 are the variable of type struct record. There are two ways to
declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
Accessing structure members
The link between a member and a variable is established using the member operator ‘.’
Which is also known as ‘dot operator’. For example:
[Link] = 201;
strcpy([Link], “Bhagirath”);
We can also use scanf function to give the values through the keyboard. To access pointer
variable, we use the -> (arrow operator).
Structure Initialization
Like any other data type, a structure variable can be initialized at compile time like:
struct record
{
int rollno;
char name[20];
float per;
};
struct record student1 = { 201, “Bhagirath”, 88.0 };
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 1
PCE Unit – 5: Programming With C 251FY3-06
Arrays of Structures
We use structures to describe the format of a number of related variables. We may declare
an array of structures, each element of the array representing a structure variable.
struct record student[50];
student[0].rollno = 101;
strcpy ( student[0].name, “Bhagirath”);
defines an array called student, that consists of 50 elements. Each element is defined to
be of the type struct record and assign values to the members.
Example:
#include <stdio.h>
struct student
{
int rollno;
char name[20];
};
int main()
{
struct student stu[5];
int i;
for( i = 0; i < 5; i++)
{
printf(“\nEnter roll Number: “);
scanf(“%d”,&stu[i].rollno);
printf(“\nEnter name: “);
gets(stu[i].name);
}
for( i = 0; i < 5; i++)
{
printf(“\nRoll Number: %d”, stu[i].rollno);
printf(“\nName: %s“, stu[i].name);
}
return 0;
}
Structures within Structures
Structure within a structure means nesting of structures. Nesting of structures is permitted
in C. For example:
struct record
{
int rollno;
char name;
struct
{
int phy;
int che;
int math;
} marks;
} student;
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 2
PCE Unit – 5: Programming With C 251FY3-06
The record structure contains a member named marks, which itself is a structure with three
members.
An inner-most member in a nested structure can be accessed by chaining all the concerned
structure variable with the member using dot operator. For example:
[Link] = 83;
Example:
#include <stdio.h>
struct student
{
int rollno;
char name[30];
struct marks
{
int eng, math;
float per;
} score;
};
int main()
{
struct student obj = {101, "Bhagirath", 87, 76};
[Link] = ([Link] + [Link]) / 2;
printf("\nRecord is: \n");
printf("\nRoll Number: %d", [Link]);
printf("\nName : %s", [Link]);
printf("\nMarks in eng: %d", [Link]);
printf("\nMarks in math: %d", [Link]);
printf("\nPercentage: %.2f", [Link]);
return 0;
}
Passing Structure to a Function
There are three methods by which the values of a structure can be transferred from one
function to another:
1. The first method is to pass each member of the structure as an actual argument.
2. The second method involves passing of a copy of the entire structure.
3. The third method employs passing address of a structure to a function.
The general format of sending a copy of a structure to the called function is:
Function_name ( structure_variable );
When a structure is used as an argument to a function, the entire structure is passed using
the call by value method. When using a structure as a parameter, remember that the type of
the argument must match the type of the parameter.
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 3
PCE Unit – 5: Programming With C 251FY3-06
Example: Passing structure to a function.
#include <stdio.h>
struct student
{
int rollno;
char name[20];
};
void display(sturct student);
int main()
{
sturct student obj = {101, “Bhagirath”};
display(obj);
return 0;
}
void display(struct student ob)
{
printf(“\nName = %s”,[Link]);
printf(“\nRoll Number = %d”,[Link]);
}
Self Referential Structures
structure which contain a member field that point to the same structure type are called
self referential structures. Each structure consist of two fields, one containing the item,
and the other containing the address of the next item (a pointer to the next item). For
example:
struct node
{
int code;
struct node *next;
};
Such a structure is also called dynamic data structure. Using self-referential structure, a
list can grow or shrink in size during the execution of a program. This list does not waste
memory space. It uses the memory that is just needed for the list at any point of time.
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 4
PCE Unit – 5: Programming With C 251FY3-06
Union
Like structures, union is a user defined data type. In union, all members share the same
memory location. This implies that, although 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 follows:
union item
{
char c;
int m;
float x;
} code;
This declares a variable code of type union item. The union contains three members,
each with a different data type. However, we can use only one of them at a time. The
compiler allocates a piece of storage that is large enough to hold the largest variable type
in the union.
Example: To illustrate difference between structure and union.
#include <stdio.h>
struct snumber
{
int num;
char ch;
double d;
}sobj;
union unumber
{
int num;
char ch;
double d;
}uobj;
int main()
{
printf("\nSize of sobj = %d bytes",sizeof(sobj));
printf("\nSize of uobj = %d bytes",sizeof(uobj));
return 0;
}
Output:
Size of sobj = 16 bytes
Size of uobj = 8 bytes
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 5
PCE Unit – 5: Programming With C 251FY3-06
Difference between Structure and Union
Key
Structure Union
Difference
The keyword struct is used to The keyword union is used to
keyword
define a structure. define a union.
When a variable is When a variable is associated
associated with a structure, with a union, the compiler
the compiler allocates the allocates the memory by
Size memory for each member. considering the size of the largest
The size of structure is memory. So, size of union is
greater than or equal to the equal to the size of largest
sum of sizes of its members. member.
Each member within a
Memory allocated is shared by
Memory structure is assigned unique
individual members of union.
storage area of location.
Altering the value of a Altering the value of any of the
Value
member will not affect other member will alter other member
Altering
members of the structure. values.
Accessing Individual member can be Only one member can be
Members accessed at a time. accessed at a time.
Initialization Several members of a Only the first member of a union
of Members structure can initialize once. can be initialized.
Enumerated Data Type
The enumerated data type gives us an opportunity to invent our own data type and define
what values the variable of this data type can take. This can help in making the program
listings more readable.
enum dept
{
mca = 21, mba = 11, btech = 10, bca = 30
};
enum dept s1,s2,s3;
Now we can give values to these variables.
s1 = mca;
s2 = bca;
Internally, the compiler treats the enumerator as integers. Each value on the list of
permissible values corresponds to an integer, starting with 0. This way of assigning
numbers can be overridden by the programmer by initializing the enumerators to different
integer values.
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 6
PCE Unit – 5: Programming With C 251FY3-06
File Management in C
A computer system stores programs and data in secondary storage in the form of files.
Storing programs and data permanently in main memory is not preferred due to the
following reasons:
Main memory is usually too small to permanently store all the needed programs
and data.
Main memory is a volatile storage device, which loses its contents when power is
turned off.
It is therefore necessary to have a more flexible approach where data can be stored on
the disks and read whenever necessary, without destroying the data. This method
employs the concept of files to store data. A file is a place on the disk where a group of
related data is stored.
File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed on a
file:
Creation of the new file
Opening an existing file
Reading from the file
Writing to the file
Deleting the file
To perform file operations in C, the important file handling functions that are available in
the C library are:
Function Name Operation
fopen() Creates a new file or Open an existing file for use.
fclose() Closes a file which has been opened for use.
getc() or fgetc() Reads a character from a file.
putc() or fputc() Writes a character to a file.
getw() or fgetw() Reads an integer from a file.
putw() or fputw() Writes an integer to a file.
fprintf() Writes a set of data values to a file.
fscanf() Reads a set of data values from a file.
fseek() Sets the position to a desired point in the file.
Gives the current position in the file (in terms of bytes from
ftell()
the start).
rewind() Sets the position to the beginning of the file.
Defining and Opening a File
Data structure of a file is defined as FILE in the library of standard I/O function definitions.
When we open a file, we must specify what we want to do with the file. For example, we
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 7
PCE Unit – 5: Programming With C 251FY3-06
may write data to the file or read the already existing data. Following is the general format
for declaring and opening a file:
FILE *fptr;
fptr = fopen (“filename”, “mode”);
The first statement declares the variable fptr as a ‘pointer to the data type FILE’. The
second statement specifies the purpose of opening this file. Mode can be one the
following:
r open the file for reading only.
w open the file for writing only.
a open the file for appending (or adding) data to it.
Closing a File
A file must be closed as soon as all operations on it have been completed. This ensures
that all outstanding information associated with the file is flushed out from the buffers and
all links to the file are broken. It also prevents any accidental misuse of the file. The I/O
library supports a function to do this. It takes the following form:
fclose (file_pointer);
This would close the file associated with the FILE pointer file_pointer.
Input/Output Operations on Files
The getc and putc functions
The simplest file I/O function are getc and putc. These functions handle one character at
a time.
putc ( ch, fptr );
writes the character contained in the character variable ch to the file associated with FILE
pointer fptr.
ch = getc ( fptr );
would read a character from the file whose file pointer is fptr.
The getw and putw Functions
The getw and putw are integer-oriented function. They are used to read and write
integer values. The general forms of getw and putw are as follows:
putw ( int_num , fptr );
int_num = getw ( fptr );
The fprintf and fscanf Functions
The functions fprintf and fscanf perform I/O operations that are identical to the familiar
printf anf scanf functions, except that they work on files. The first argument of these
functions is a file pointer which specifies the file to be used. General form of fprintf is:
fprintf ( fptr, “control string” , list);
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 8
PCE Unit – 5: Programming With C 251FY3-06
where fptr is a file pointer associated with a file that has been opened for writing. The
control string contains output specifications for the items in the list.
The general format of fscanf is:
fscanf ( fptr, “control string”, list);
This statement would cause the reading of the items in the list from the file specified by
fptr, according to the specifications contained in the control string.
Error Handling During I/O Operations
It is possible that an error may occur during I/O operations on a file. Typical error
situations include the following:
Trying to read beyond the end-of-file mark.
Device overflow.
Trying to use a file that has not been opened.
Trying to perform an operation on a file, when the file is opened for another type of
operation.
Opening a file with an invalid filename.
Attempting to write to a write-protected file.
We have two status-inquiry library function, feof and ferror that can help us detect I/O
errors in the files.
The feof function can be used to test for an end of file condition. It takes a FILE pointer
as its only argument and returns a nonzero integer value if all of the data from the
specified file has been read, and returns zero otherwise.
if ( feof ( fptr ) )
printf(“End of file”);
The ferror function reports the status of the file indicated. It also takes a FILE pointer as
its argument and returns a nonzero integer if an error has been detected up to that point,
during processing. It returns zero otherwise.
if ( ferror( fptr ) != 0 )
printf (“Error occurred”);
Whenever a file is opened using fopen function, a file pointer is returned. If the file
cannot be opened for some reason, then the function returns a NULL pointer. This facility
can be used to test whether a file has been opened or not.
if ( fptr == NULL )
printf (“File opening Error”);
Example: A program to print the file contents in uppercase.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("[Link]","r");
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 9
PCE Unit – 5: Programming With C 251FY3-06
if(fp == NULL)
{
puts("File opening error.");
exit(1);
}
do
{
ch = fgetc(fp);
putchar(toupper(ch));
} while(ch != EOF);
return 0;
}
Example: A program to copy the contents of a file and write it in another file. (file
copy program).
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1, *fp2;
char ch;
fp1 = fopen("[Link]", "r");
if (fp1 == NULL)
{
puts("File opening error.");
exit(1);
}
fp2 = fopen("[Link]", "w");
if (fp2 == NULL)
{
puts("File opening error.");
exit(1);
}
do
{
ch = fgetc(fp1);
fputc(ch, fp2);
} while (ch != EOF);
_fcloseall();
printf("\nThe contents of [Link]:\n");
fp1 = fopen("[Link]", "r");
do
{
ch = fgetc(fp1);
putchar(ch);
} while (ch != EOF);
fclose(fp1);
return 0;
}
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 10
PCE Unit – 5: Programming With C 251FY3-06
Random Access to Files
There are occasions, however, when we are interested in accessing only a particular part
of a file and not in reading the other parts. This can be achieved with the help of the
functions fseek, ftell, and rewind available in the I/O library.
ftell takes a file pointer and return a number of type long, that corresponds to the current
position. It takes the following form:
pos = ftell ( fptr );
rewind takes a file pointer and resets the position to the start of the file.
rewind ( fptr );
fseek function is used to move the file position to a desired location within the file. It
takes the following form:
fseek ( fptr, offset, position );
Here fptr is a pointer to the file concerned, offset specifies the number of positions
(bytes) to be moved from the location specified by position. The position can take one
of the following three values:
0 for beginning of file
1 for current position
2 for end of file
Example:
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("file3.c","r+");
fseek(fp,-1,2);
printf("\nTotal Characters in File: %d",ftell(fp));
printf("\nLast character is: %c",fgetc(fp));
fseek(fp,0,0);
printf("\nFirst character is: %c",fgetc(fp));
fseek(fp,4,1);
printf("\nSixth character is: %c",fgetc(fp));
rewind(fp);
printf("\nAgain! First character is: %c",fgetc(fp));
fclose (fp);
return 0;
}
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 11
PCE Unit – 5: Programming With C 251FY3-06
Command Line Arguments
The arguments passed from command line are called command line arguments. These
arguments are handled by main() function. Command line argument is a parameter
supplied to a program when the program is invoked. This parameter can be of any type.
In fact main can take two arguments called argc and argv and the information contained
in the command line is passed on to the program through these arguments, when main is
called up by the system.
The variable argc is an argument counter that counts the number of arguments on the
command line. The argv is an argument vector and represents an array of character
pointers that point to the command line arguments. In order to access the command line
arguments, we must declare the main function and its parameters as follows:
main ( int argc, char *argv[ ] )
{
…..
…..
}
The first parameter in the command line is always the program name and therefore
argv[0] always represents the program name.
Example:
#include <stdio.h>
void main(int argc, char *args[]) {
int i;
for(i = 0; i < argc; i++)
{
printf("\nArgument args[%d] is: %s",i,args[i]);
}
}
Example: Add two numbers using command line arguments.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char*args[])
{
int n1, n2, sum;
if(argc != 3)
{
printf("Arguments must be: \"programName value1 value2\"");
exit(1);
}
n1 = atoi(args[1]);
n2 = atoi(args[2]);
sum = n1 + n2;
printf("\nSum = %d",sum);
return 0;
}
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 12