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

BPOPS103/203 Module 5 Notes

The document provides an overview of structures, unions, and enumerated data types in C programming, focusing on the definition, declaration, initialization, and access of structures. It explains how to create and manipulate structures, including examples of passing structures to functions and using nested structures. Additionally, it discusses the concept of arrays of structures for managing collections of related data.

Uploaded by

Hamza Hafeel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

BPOPS103/203 Module 5 Notes

The document provides an overview of structures, unions, and enumerated data types in C programming, focusing on the definition, declaration, initialization, and access of structures. It explains how to create and manipulate structures, including examples of passing structures to functions and using nested structures. Additionally, it discusses the concept of arrays of structures for managing collections of related data.

Uploaded by

Hamza Hafeel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Module-V Structures,Union and Enumerated Data Types, Files

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.

Structure variable declaration:


When a structure is defined, it creates a user-defined type but, no storage is allocated.
For the above structure of person, variable can be declared as:
struct person
{
char name[50];
int cit_no;
float salary;
};

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 1


Inside main function:
struct person p1, p2, p[20];
Another way of creating sturcture variable is:
struct person
{
char name[50];
int cit_no;
float salary;
}p1 ,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct
person are created.
Accessing members of a structure
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->)
Any member of a structure can be accessed as: structure_variable_name.member_name
Suppose, we want to access salary for variable p2. Then, it can be accessed as:
p2.salary
Example of structure
Write a C program to add two complex numbers using structure.
#include <stdio.h>
struct complex {
float real;
float imag;
};

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

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 2


C Structure Initialization:
When we declare a structure, memory is not allocated for un-initialized variable. We can
initialize structure variable in different ways -
Way 1: Declare and Initialize
struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after declaration
we have initialized the structure variable.

std1 = { "Pritesh",67,78.3 }

This is the code for initializing structure variable in C programming

Way 2 : Declaring and Initializing Multiple Variables


struct student
{
char name[20];
int roll;
float marks;
}

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

Way 3 : Initializing Single member


struct student
{
int mark1;
int mark2;

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 3


int mark3;
} sub1={67};
Though there are three members of structure, only one is initialized, and then remaining two
members are initialized with Zero. If there are variables of other data type then their initial
values will be -

Data Type Default value if not initialized

integer 0

float 0.00

char NULL

Way 4: Initializing inside main


struct student
{
int mark1;
int mark2;
int mark3;
};

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

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 4


We need to initialize structure variable to allocate some memory to the structure.

struct student s1 = {89,54,65};

Accessing and Processing a Structure:


The members of structure can be accessed and processed as separate entities. A structure
members can be accessed by using dot (.) also called period operator. The syntax is
Variable.member
Where Variable refers to the name of a structure type variable and member refers to the name of
a member within the structure.
The following program demonstrate the accessing of structure.
/* Simple program to demonstrate the accessing of structure */
#include<stdio.h>
#include<string.h>
struct date
{
int day;
int year;
char month_name[10];
};
main()
{
struct date d;
d.day=25;
strcpy(d.month_name,”January”);
d.year=2006;
printf(“Day=%d Month=%s Year=%d\n”, d.day, d.month_name, d.year);
}
Output:
Day=25 Month=January Year=2006

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.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 5


The following figure shows the array of structure student. It can store information of 40 student
in the class.
Field 1 Field 2 Field 3 Field 4

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

Example program for array of structures in C:


Implement structures to read, write and compute average marks and the students scoring above
and below average marks for class of N students.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 6


/* Program to read, write and compute average marks and the students scoring above and
below average marks*/
#include <stdio.h>
struct student
{
char usn[50];
char name[50];
int marks;
} s[10];
void main()
{
int i,n,countav=0,countbv=0;
float sum,average;
printf("Enter number of Students\n");
scanf("%d",&n);
printf("Enter information of students:\n");
// storing information
for(i=0; i<n;i++)
{
printf("Enter USN: ");
scanf("%s",s[i].usn);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("\n");
}
printf("Displaying Information:\n\n");
// displaying information
for(i=0; i<n; i++)
{
printf("\nUSN: %s\n",s[i].usn);
printf("Name: %s\n ", s[i].name);
printf("Marks: %d",s[i].marks);
printf("\n");
}
for(i=0;i<n;i++)
sum=sum+s[i].marks;
average=sum/n;
printf("\nAverage marks: %f",average);
for(i=0;i<n;i++)
{
if(s[i].marks>=average)
countav++;
else
Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 7
countbv++;
}
printf("\nTotal No of students above average= %d",countav);
printf("\nTotal No of students below average= %d",countbv);
}

Structures and Functions:


Passing structure to function in C:

It can be done in below 3 ways.

1. Passing structure to a function by value


2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global

Passing Structure Members to Function:


We can pass a member of a structure to a function by passing its value to the function. For
example, consider this structure:
struct demo
{
int i;
double d;
char s[10];
}var1;
We can pass individual members to the function using following statements:
func(var1.i); /* passes integer value of i */
func1(var1.d); /* passes double float value of d*/
func2(var1.d); /* passes address of string s */
func3(var1.s[2]); /* passes character value of s[2] */
In each case, it is the value of a specific element that is passed to the function. It does not matter
that the element is part of a larger unit. It is also possible to pass the address of an individual
member of structure. For that, we have to put AND operator before the structure name. for
exampe, to pass the address of the members of the structure var1, we have to write:
func(&var1.i); /* passes address of integer i */
func1(&var1.d); /* passes address of double float d*/
func2(&var1.d); /* passes address of string */
func3(&var1.s[2]); /* passes address of character s[2] */

Passing Entire Structures to Functions:


In C, structure can be passed to functions by two methods:

1. Passing by value (passing actual value as argument)


2. Passing by reference (passing address of an argument)

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 8


Passing structure by value
A structure variable can be passed to the function as an argument as normal variable. If structure
is passed by value, change made in structure variable in function definition does not reflect in
original structure variable in calling function.

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

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 9


inch) to add function by reference and display the result in main function without
returning it.
#include <stdio.h>
struct distance{
int feet;
float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3);
int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet);
printf("Enter inch: ");
scanf("%f",&dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d",&dist2.feet);
printf("Enter inch: ");
scanf("%f",&dist2.inch);
Add(dist1, dist2, &dist3);

/*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.

Structure within Structure: Nested Structure


Nested structure in C is nothing but structure within structure. One structure can be declared
inside other structure as we declare structure members inside a structure. The structure variables
can be a normal structure variable or a pointer variable to access the data.
 Structure written inside another structure is called as nesting of two structures.

 Nested Structures are allowed in C Programming Language.


 We can write one Structure inside another structure as member of another structure.
Way 1 : Declare two separate structures
struct date
{
int date;
int month;
int year;
};

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 :

Accessing Month Field : emp1.doj.month


Accessing day Field : emp1.doj.day

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 11


Accessing year Field : emp1.doj.year

Way 2 : Declare Embedded structures


struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp1;
Accessing Nested Members :

Accessing Month Field : emp1.doj.month


Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year

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

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 12


The union tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the union's definition, before
the final semicolon, you can specify one or more union variables but it is optional. Here is the
way you would define a union type named Data having three members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union −
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}

When the above code is compiled and executed, it produces the following result −
Memory size occupied by data: 20

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 13


Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access. You would use the keyword union to define variables of union type. The
following example shows how to use unions in a program −
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

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

union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);

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.

Similarities between Structure and Union:

The following are the similarities between structure and union:

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

Difference between Structure and Union:

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.

Enumerated Data Type:


Syntax to Define Enum in C
An enum is defined by using the „enum‟ keyword in C, and the use of a comma separates the
constants within. The basic syntax of defining an enum is:

enum enum_name{int_const1, int_const2, int_const3, …. int_constN};

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.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 16


enum cars{BMW, Ferrari, Jeep, Mercedes-Benz};

Here, the default values for the constants are:


BMW=0, Ferrari=1, Jeep=2, and Mercedes-Benz=3. However, to change the default values, you
can define the enum as follows:
enum cars{
BMW=3,
Ferrari=5,
Jeep=0,
Mercedes-Benz=1
};
Enumerated Type Declaration to Create a Variable
Similar to pre-defined data types like int and char, you can also declare a variable for enum and
other user-defined data types. Here‟s how to create a variable for enum.
enum condition (true, false); //declaring the enum
enum condition e; //creating a variable of type condition
Suppose we have declared an enum type named condition; we can create a variable for that data
type as mentioned above. We can also converge both the statements and write them as:
enum condition (true, false) e;
For the above statement, the default value for true will be 1, and that for false will be 0.

How to Create and Implement Enum in C Program


Now that we know how to define an enum and create variables for it, let‟s look at some
examples to understand how to implement enum in C programs.
Example 1: Printing the Values of Weekdays
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main(){
// printing the values of weekdays
for(int i=Sunday;i<=Saturday;i++){
printf("%d, ",i);
}
return 0;
}
Output:

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

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 17


for the other days as the previous value plus 1. To iterate through the enum and print the values
of each day, we have created a for loop and initialized the value for i as Sunday.

Example 2: Assigning and Fetching Custom Values of Enum Elements


#include<stdio.h>
enum containers{
cont1 = 5,
cont2 = 7,
cont3 = 3,
cont4 = 8
};
int main(){
// Initializing a variable to hold enums
enum containers cur_cont = cont2;
printf("Value of cont2 is = %d \n", cur_cont);
cur_cont = cont3;
printf("Value of cont3 is = %d \n", cur_cont);
cur_cont = cont1;
printf("Value of hearts is = %d \n", cur_cont);
return 0;
}
Output:

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.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 18


Functions use in File Handling in C

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.

How file handling works

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.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 19


Declaring a File Pointer

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

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 20


If the file locates at abc.txt does not already exist, then fopen() will return NULL, so it is better
to check the value returned from the fopen () function in an if statement to make sure that the
file is there.
if ( (fptr = fopen( "abc. txt", "r")) == NULL) {
printf("cannot open abc.txt\n");
}
Note: There is a limit to the number of files you can open at a particular time. It determines by
the value of the constant FOPEN_MAX that defines in stdio.h. FOPEN_MAX is an integer that
specifies the maximum number of files that can be open at a time. In C, it is 5.
File Opening Modes

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.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 21


Closing a File

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.

Input /Output operations on files:

The getc and putc functions:

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.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 22


Example
Following is the C program for using putc() and getc() functions −

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

The fprintf and fscanf functions:


The functions fprintf and fscanf perform I/O operations that are identical to the familiar printf
and scanf functions, except of course that they work on files. The first argument of these
functions is a file pointer which specifies the file to be used. The general form of fprintf is,

fprintf(fp, “control string”, list);


where fp is a file pointer associated with a file that has been opened for writing. The control
staring contains output specifications for the items in the list. The list may include variables,
constants and strings. Example:
fprintf(f1, :%s%d%f:, name, age, 7.5);
here, name is an array variable of type char and age is an int variable.

The general format of fscanf is


fscanf(fp, “control string”, list);

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 23


This statement would cause the reading of the items in the list from the file specified by fp,
according to the specifications contained in the control string.
Example: fscanf(f2, “%s%d”, item, &quantity);
Like scanf, fscanf also returns the number of items that are successfully read. When the end of
file is reached, it returns the value EOF.

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

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 24


printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
Review Questions
1. What is a structure? How does a structure differ from an array? (4 Marks)
2. What is a structure member? What is a relationship between a structure member and a
structure?(4 Marks)
3. Describe the syntax of defining a composition of structure. (4 Marks)
4. How can structure variables be declared? How do structure variable declarations differ
from structure type declarations? (5 Marks)
5. How is structure initialized? (4 Marks)
6. How is an array of structures initialized? (5 Marks)
7. How is a structure member accessed? (4 Marks)
8. Write note on: i) Arrays within structures ii) Arrays of structures. (4 Marks)
9. How can a structure member be processed? (4 Marks)
10. What is nested structure? Explain with example. (6 Marks)
11. How can structure members be passed to a function? (5 Marks)
12. How can an entire structure be passed to a function? (6 Marks)
13. Write a C program that accepts a structure variable as parameters to a function from a
function call. (10 Marks)
14. Write a C program to read details of 10 students and to print the marks of the student if
his name is given as input.
15. Implement structures to read, write and compute average marks and the students scoring
above and below average marks for class of N students. (12 Marks)
16. What is enumerated data type? How to create and implement enum in C? Explain with
examples. (6 Marks)
17. How to create file in C? Explain with examples. (5 Marks)
18. What are the different file opening modes? Explain with examples. (8 Marks)
19. How to perform input and output operations on files in C? Explain with examples. (6
Marks)
20. How to close the file operation in C? Explain with example. (4 Marks)

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 25

You might also like