BPOPS103/203 Module 5 Notes
BPOPS103/203 Module 5 Notes
Structure in C:
C arrays allow us to define type of variables that can hold several data items of the same
kind but structure is another user defined data type available in C programming, which allows
us to combine data items of different kinds.
Defining a Structure:
Structure is the collection of variables of different types under a single name for
better handling. For example: we want to store the information about person about
his/her name, citizenship number and salary. We can create these information separately
but, better approach will be collection of these information under single name because
all these information are related to person.
In C, a structure is a derived data type consisting of a collection of member elements and
their data types. Thus, a variable of a structure type is the name of a group of one or more
members which may or may not be of the same data type. In programming terminology, a
structure data type is referred to as a record data type and the members are called fields.
Keyword struct is used for creating a structure.
Syntax of structure:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
We can create the structure for a person as mentioned above as:
struct person
{
char name[50];
int cit_no;
float salary;
};
This declaration above creates the derived data type struct person.
void main()
{
struct complex n1,n2,sum;
printf("For 1st complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);
sum.real=n1.real+n2.real;
sum.imag=n1.imag+n2.imag;
printf("Sum = %.1f + %.1fi", sum.real, sum.imag);
}
std1 = { "Pritesh",67,78.3 }
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
In this example, we have declared two structure variables in above code. After declaration of
variable we have initialized two variable.
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
integer 0
float 0.00
char NULL
void main()
{
struct student s1 = {89,54,65};
- - - - --
- - - - --
- - - - --
};
When we declare a structure then memory won‟t be allocated for the structure. i.e only writing
below declaration statement will never allocate memory
struct student
{
int mark1;
int mark2;
int mark3;
};
Array of Structures:
When we are working with a group of entities and their attributes, we need to create array
of structures. C Structure is collection of different data types (variables) which are grouped
together. Whereas, array of structures is nothing but collection of structures. This is also called as
structure array in C.
For example, if we want to work with students data base we can create a structure student, in
which we can store the information about the address, age, marks obtained by ther student and so
on. By creating an array of structure student we can store information of group of students. Then
by accessing aray of structure student we can quickly and easily work with student‟s
information.
Student A[0]
Student A[1]
Student A[39]
Structure is used to store the information of One particular object but if we need to store such
100 objects then Array of Structure is used.
Example :
struct Bookinfo
{
char bname[20];
int pages;
int price;
}Book[100];
Explanation :
1. Here Book structure is used to Store the information of one Book.
2. In case if we need to store the Information of 100 books then Array of Structure is used.
3. b1[0] stores the Information of 1st Book , b1[1] stores the information of 2nd Book and So
on We can store the information of 100 books.
Accessing Pages field of Second Book :
Book[1].pages
Write a C program to create a structure student, containing name and roll. Ask user the name and
roll of a student in main function. Pass this structure to a function and display the information in
that function.
#include <stdio.h>
struct student{
char name[50];
int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration otherwise compiler shows
error */
int main(){
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as argument
return 0;
}
void Display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
Output
Enter student's name: Kevin Amla
Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149
Passing structure by reference
The address location of structure variable is passed to function while passing it by reference. If
structure is passed by reference, change made in structure variable in function definition reflects
in original structure variable in the calling function.
Write a C program to add two distances(feet-inch system) entered by user. To solve this
program, make a structure. Pass two structure variable (containing distance in feet and
/*passing structure variables dist1 and dist2 by value whereas passing structure variable dist3
by reference */
printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);
return 0;
}
void Add(struct distance d1,struct distance d2, struct distance *d3)
{
/* Adding distances d1 and d2 and storing it in d3 */
d3->feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12) { /* if inch is greater or equal to 12, converting it to feet. */
d3->inch-=12;
++d3->feet;
}
}
Output
First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 10
Enter inch: 7.5
Sum of distances = 18'-2.3"
In this program, structure variables dist1 and dist2 are passed by value (because value
of dist1and dist2 does not need to be displayed in main function) and dist3 is passed by
reference, i.e, address of dist3 (&dist3) is passed as an argument. Thus, the structure pointer
variable d3points to the address of dist3. If any change is made in d3 variable, effect of it is seed
in dist3variable in main function.
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;
Accessing Nested Elements :
1. Structure members are accessed using dot operator.
2. „date„ structure is nested within Employee Structure.
3. Members of the „date„ can be accessed using „employee‟
4. emp1 & doj are two structure names (Variables)
Explanation Of Nested Structure :
Unions:
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining
a structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
union Data {
int i;
float f;
char str[20];
};
int main( ) {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data: 20
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the
value of str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time
which is the main purpose of having unions −
#include <stdio.h>
#include <string.h>
Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 14
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.
Both structure and union are the custom data types that store different types of data
together as a single entity
The members of structure and union can be objects of any type, such as other structures,
unions, or arrays.
Both union and a structure can be passed by value to a function and also return to the
value by functions. The argument will need to have the same type as the function
parameter.
Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 15
To access members, we use the „.‟ operator.
Both a structure and a union combine different information related to a given entity. The main
difference between the two is how specific information is stored and accessed. The table below
highlights the key differences between structure and union:
Structure Union
We use the struct statement to define a We use the union keyword to define a union.
structure.
Every member is assigned a unique memory All the data members share a memory
location. location.
Change in the value of one data member does Change in the value of one data member
not affect other data members in the structure. affects the value of other data members.
You can initialize multiple members at a time. You can initialize only the first member at
once.
A structure can store multiple values of the A union stores one value at a time for all of its
different members. members
A structure‟s total size is the sum of the size of A union‟s total size is the size of the largest
every data member. data member.
Users can access or retrieve any member at a You can access or retrieve only one member at
time. a time.
In the above syntax, the default value of int_const1 is 0, int_const2 is 1, int_const3 is 2, and so
on. However, you can also change these default values while declaring the enum. Below is an
example of an enum named cars and how you can change the default values.
In the above code, we declared an enum named days consisting of the name of the weekdays
starting from Sunday. We then initialized the value of Sunday to be 1. This will assign the value
We have declared an enum named containers with four different containers as the elements in the
above code. We have then given custom values to the elements and initialized the variable for
the enum multiple times to print the relevant output.
File Management in C:
The C language file handling principle used to archive the data on the disc permanently. This
idea helps us to preserve our data in secondary (hard disc) memory. Both associated files are
accessible in the header package stdio.h.
Function Description
fopen() To create a file.
fclose() To close an existing file.
getc() Read a character from a file.
putc() Write a character in file.
fprintf() To write set of data in file.
fscanf() To read set of data from file.
getw() To read an integer from a file.
putw() To write an integer in file.
Once we compile and run a program, it gets the output, but the result isn‟t saved anywhere in
the framework as details.
What if we want to store the outcome for future references? After all, most tech companies
compose programmes to store the results as records. By integrating file handling in C, this issue
can easily be overcome. Since most computer systems use files to, store information, C offers
this advantage of file handling.
Need for File Handling in C
There was a moment when the result generated when the software is compiled and output is not
expected. If we wish to review the performance many times, compiling and running the same
software several times is a repetitive job. It is where the files handling falls into effect. Below
are some of the following explanations for file management‟s popularity:
• Reusability: helps to retain the data collected after the software is run.
• Huge storage capacity: you don‟t need to think about the issue of mass storage using data.
• Save time: Unique applications need a lot of user feedback. You can quickly open some
aspect of the code using special commands.
• Portability: You can quickly move file material from one operating device to another without
thinking about data loss.
Before opening a file, you have to declare a pointer to a structure of type FILE called a file
pointer. The FILE type is a structure that contains information needed for reading and writing a
file. The information generally includes the operating system‟s name for the file, the current
character position in the file, whether the file is being read or written and so on. This structure
declares within the header file stdio. h. The declaration of the file pointer made as follows,
FILE *fp; //fp is the name of the file pointer
Here fp is declared as a pointer to a structure of type FILE.
Opening a file – for creation and edit
Once the file pointer has been declared, the next step is to open an appropriate file to perform
any operation. This is done using the function fopen(), specified in the header file stdio.h. To
open a file as standard I/O, the syntax is:
fp =FILE* fopen(const char* filename, const char* mode);
The fopen() function takes two parameters, both of which are strings. The parameter filename is
the name of the disk file to open. The file name generally consists of two parts: a primary name
and an optional extension, which separates from the primary name by a period (. ). The rules for
naming files are determined by your operating system, for example, in MS-DOS. The maximum
size of the primary name is 8 characters, and that of an extension is 3 characters.
Some valid file names in the MS-DOS system are abc.txt, temp, result.dat etc. when you want
to specify the full pathname for the file, use double slash (\\) or single forward-slash (/) as in
UNIX and not a single backslash.
The second parameter mode specifies how the file is to be opened, i.e. for reading, writing both
reading and writing, appending at the end of the file etc. Allowable modes include read (“r”),
write (“w”) and append (“a”) etc.
If the call to the fopen () function is successful, the function returns a pointer of type FILE. This
pointer must use in subsequent operations on the file, such as reading from or writing. If the file
cannot open for some reason, fopen () returns a NULL pointer. ·
Now, if fptr is a file pointer pointing to type FILE that you have declared earlier, then the
statement,
fptr = fopen( "abc.txt", "r");
opens a text file with the name “abc.txt” and associates it with the file pointer fptr. Because you
have specified the mode “r,” so you can only read the file, but you can‟t write to this file. The
file position will set to the beginning of the data in the file.
If the file locates at C:\mydata\abc.txt, then the string used in the fopen() function should be
C:\\mydata\\abc. txt so the statement should be
fptr = fopen( "C:\\mydata\\abc. txt", "r");
The three basic file operations are reading, writing and appending. These operations can specify
a file by using the appropriate file mode. Following are the different modes used with the fopen
() function to determine what kind of process is to do to that file :
(a) Read Mode (r): If the file mode is r, it only allows reading from an existing file. The file
position will set to the beginning of data in the file. If the file does not exist, it returns NULL It.
It should note that the file can only be read, not written.
(b) Write Mode (w): If the file mode is w, it only allows writing to a file. If the file does not
exist, a new file with the specified filename created, and the file position will set to the
beginning of data in the file. If the file already exists, it will destroy, and a new empty file will
create, i.e. its contents are overwritten.
(c) Append Mode (a): Like w mode, the append mode (a) also allows writing to a file but
allows writing only at the end of the file. If the file does not exist, a new file with the specified
filename creates as in w. However, unlike w, if a file already exists, it will merely reopen, not
destroyed first.
(d) Read+ (r+): It is an extension to read mode (r). As with reading mode, a file will open. It
not only allows to read a file but also allows to write to it. However, if the file does not already
exist, the open operation will fail.
(e) Write+ (w+): It is an extension to write mode (w). As with write mode, a file will create. It
not only allows us to write to a file but also to read from it. If a file already exists, it will be first
destroyed and then created as an empty file.
(f) Append+ (a+): It opens or creates a file for update. It is similar to append Mode, but its
operations are to read existing contents and add new contents at the end of the file, but cannot
modify existing contents. The file position pointer is set to point to a first character if a read
operation is executed. The file position pointer is set to the last position if a write operation is to
execute.
When all operations on a file have complete, it must be closed. As a result, the file disassociates
from the file pointer. What happens during a write to a file is that data not written immediately,
but it stores in a buffer. When the buffer is full, all its contents write to the disk.
Closing the file flushes the data left in the buffer to ensure that no data will be lost before it
disassociates the file pointer with the opened file.
Although when the program exits, all open files are closed automatically, however explicitly
closing a file has the following advantages,
• Prevents accidental misuse of the file.
• As there is a limit to the number of files that can keep open simultaneously, closing a file may
help open another file.
• The closed file can again open in a different mode as per requirement.
In C, a file is closed by the function fclose(). It has the following syntax,
fclose(FILE* fp);
This function accepts a file pointer as an argument and returns a value of type int.
If the fclose() function closes the file successfully, then it returns an integer value 0. Otherwise,
it returns EOF. It usually fails when there is no more space left on the disk or removed before
the function calls.
Disassociates the file pointer fp with the filename associated earlier in fopen(), so fp can no
longer access the file it represented.
The simplest file I/O functions are getc and putc. These are analogous to getchar and putchar
functions and handle one character at a time. Assume that a file is opened with mode w and file
pointer fp1. Then the statement
putc(c, fp1);
writes the character contained in the character variable c to the file associated with FILE pointer
fp1. Similarly, getc is used to read a character form a file that has been opened in read mode. For
example, the statement,
c=getc(fp2);
would rad a character from the file whose file pointer is fp2.
The file pointer move by one character position for every operation of getc or putc. The getc will
return an end-of-file marker EOF, when end of file has been reached. Therefore, the reading
should be terminated when EOF is encountered.
#include<stdio.h>
int main(){
char ch;
FILE *fp;
fp=fopen("std1.txt","w"); //opening file in write mode
printf("enter the text.press cntrl Z:");
while((ch = getchar())!=EOF){
putc(ch,fp); // writing each character into the file
}
fclose(fp);
fp=fopen("std1.txt","r");
printf("text on the file:");
while ((ch=getc(fp))!=EOF){ // reading each character from file
putchar(ch); // displaying each character on to the screen
}
fclose(fp);
return 0;
}
Example:
The following program illustrates the use of fscanf function.
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
The following program illustrates the use of printf function.
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);