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

Unit 2 C Programming and Data Structures-1

The document covers advanced features of C programming, focusing on user-defined data types such as structures, unions, and enumerated data types, along with pointers and file handling. It explains the definitions, syntax, and operations related to structures and unions, highlighting their differences and usage in memory management. Additionally, it discusses pointers, their declaration, and how they store addresses of other variables.

Uploaded by

Malathi Krishnan
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)
3 views

Unit 2 C Programming and Data Structures-1

The document covers advanced features of C programming, focusing on user-defined data types such as structures, unions, and enumerated data types, along with pointers and file handling. It explains the definitions, syntax, and operations related to structures and unions, highlighting their differences and usage in memory management. Additionally, it discusses pointers, their declaration, and how they store addresses of other variables.

Uploaded by

Malathi Krishnan
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/ 53

C.K.

COLLEGE OF ENGINEERING AND TECHNOLOGY


CS3353 - C PROGRAMMING AND DATA STRUCTURES
UNIT II - C PROGRAMMING - ADVANCED FEATURES
Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays
and Functions – File Handling – Preprocessor Directives.

2.1 INTRODUCTION
➢ Structures, unions and enumerations are known as user defined data types.
➢ These data types are used to create a flexible new data type.
➢ Structure can be used for the storage of different data types. The similarity
between structure and array is both contain a finite number of elements.
➢ Union is similar to structures in all aspects except the manner in which their
constituent elements are stored.
➢ In structures, separate memory is allocated to each element, while in unions all
the elements are share the same memory.
➢ Enumeration helps to define a data type whose objects can take a limited set of
values.

2.2 STRUCTURE
Definition
➢ A Structure is a collection of variables of different data types under a single
name and provides a convenient way of grouping several of related information
together.
➢ Unlike arrays, it can be used for the storage of heterogeneous data (data of
different data types).

2.2.1 Three main aspects of working with structure

1.
1. Defining Structure
2. Initializing structure elements
3. Declaring variables and constants (objects) of the newly created type.

2.2.1.1 Defining Structure


Syntax
struct structure_name
{
element-1;
element-2;
element-3; //Variable declarations
...
...
element-n;
} v1,v2 ....... vn;
Where element1, element2, element3 are variables of any primitive or derived
data types and v1,v2, .. vn are structure variable.
Example
struct book
{
char author[40];
float price;
int page;
}b1,b2;
Rules for defining structure
➢ Structure definition consists of the keyword struct followed by a structure tag
name and a structure declaration list enclosed within braces.
➢ The structure declaration list consists of one or more variables declaration,
possibly of different data types. The variable names declared in the structure
declaration list are known as structure members.
➢ Structure members can be variables of the basic types( eg: char, float, int) or
➢ A structure declaration list cannot contain a member of void type or incomplete
type or function type.
➢ Self referential structure: a structure may contain a pointer to an instance of
itself is known as self referential structure.

2.2.1.2 Initializing Structure Elements


Syntax
Struct book
{
int page;
char author[10];
float price;
}b1;
Example
void main()
{
b1.author=”Kalam”;
printf(“Enter price:”);
scanf(“%f”,&b1.price);
b1.page=178;
}

2.2.1.3 Declaring Structure Objects


➢ Variables (or) constants of the created structure type can be created either at the
time of structure definition (or) after the time of structure definition.
Syntax
[type qualifier] structure type identifier name [= initialization list]; (or)
variables;
Example
struct book b1={3,2,1}; // it contains the initialization list
Rules for declaring structure objects:
➢ It is important to note that the structure members cannot be initialized during the
structure definition; however the members of a structure object can be initialized
by providing an initialization list.

2.2.2 Operations on Structures


➢ Aggregate operations
➢ Segregate operations

2.2.2.1 Aggregate Operations


➢ An aggregate operation treats an operand as an entity and operates on the entire
operand as whole instead of operating on its constituent members.
Types
a) Accessing members of an object of a structure
b) Assigning a structure object to a structure variables
c) Address of a structure object
d) Size of a structure.
a) Accessing members of an object of a structure :
The members of a structure object can be accessed by using:
(i) Direct member access operator (dot operator)
(ii) Indirect member access operator(arrow operator)
(i) Direct member access operator (dot operator):
Syntax:
struct variable-name.struct-element-name
Example Program 2.1
//C program to print student details using structure
#include<stdio.h>
#include<conio.h>
struct student
{
int rno;
float mark;
};
struct student s;
void main()
{
printf(“enter the name”);
scanf(“%c”,&s.name);
printf(“enter the rno”);
scanf(“%d”,&s.rno);
printf(“enter the mark”);
scanf(“%f”,&s.mark);
printf(“NAME=%c”,s.name);
printf(“RNO=%d”,s.rno);
printf(“MARK=%f”,s.mark);
getch();
}
OUTPUT
enter the name
xyz
enter the rno
20
enter the mark
80
NAME=xyz
RNO=20
MARK=80
Example Program 2.2
/*C program to calculate the student’s average marks and student details using
structure*/
#include<stdio.h>
#include<conio.h>
struct student
{
char name;
int rno;
int m1,m2,m3;
};
struct student s;
void main()
{
float total,average;
printf(“enter the name”);
scanf(“%c”,&s.name);
printf(“enter the rno”);
scanf(“%d”,&s.rno);
printf(“enter the marks”);
scanf("%d %d %d",&s.m1,&s.m2,&s.m3);
total=s.m1+s.m2+s.m3;
average=total/3;
printf(“NAME=%c”,s.name);
printf(“RNO=%d”,s.rno);
printf(“AVERAGE MARK=%f”,average);
getch();
}
Output:
enter the name
xyz
enter the rno
20
enter the marks
80
90
95
NAME=xyz
RNO=20
AVERAGE MARK=88.33
Example Program 2.3
#include<stdio.h>
struct book //Struct datatype declaration
{
int x,y;
};
void main()
{
struct book s1={4,5}; //s1-> variable of structure and values are
initialized
int a=10 , b=20 ;
printf(“\na=%d”,s1.x+a); // elements are accessed using dot operator(.)
printf(“\nb=%d”, s1.y+b);
}
Output:
a=4
(ii) Indirect member access operator (arrow operator)
Syntax :
struct variable name -> struct element name
(or)
*struct variable name . struct element name
Example Program 2.4
#include<stdio.h>
struct book // structure data type declaration
{
int x,y;
};
struct book *b1; //pointer to structure
void main()
{
printf(“enter the values”);
scanf(“%d”, &b1->x);
scanf(“%d”,&b1->y); //-> operator used
printf(“\nx=%d”, b1->x);
printf(“\ny=%d”, *b1.y);
}
Output:
Enter the values 10 20
x=10
y=20
b) Assigning a structure object to a structure variables
➢ Assignment operator (=) is used to assign the values of one variable to another
variable. When assignment operator (=) is applied on structure variables, it
performs member by member copy.
Example Program 2.5
#include<stdio.h>
struct book // struct datatype is declared
{
char title[25], author[20];
int price;
};
void main()
{
struct book b1,b2,b3; //structure variables are declared
b1={“ cutting stone”, “Abraham”,400};
b2.author=b1.author;
b3=b1; // b1 variable values are assigned to b3
printf(“%s by %s is of Rs. %d \n”, b1.title,b1.author,b1.price);
printf(“%s is the author of second book”,b2.author);
printf(“%s by %s is of Rs. %d \n”, b3.title,b3.author,b3.price);
}
Output:
cutting stone by Abraham is of Rs.400
Abraham is the author of second book
cutting stone by Abraham is of Rs. 400
c) Address of a structure object
➢ The address of operator (&) when applied to a structure object gives its base
address. It can also be used to find the address of the constituting members of a
structure object.
Example Program 2.6
#include<stdio.h>
struct book // struct datatype is declared
{
char title[25], author[20];
int price;
};
void main()
{
struct book b1,b2,b3; //structure variables are declared
b1={“ cutting stone”, “Abraham”,400};
b2.author=b1.author;
b3=b1; // b1 variable values are assigned to b3
printf(“%s by %s is of Rs. %d \n”, b1.title,b1.author,b1.price);
printf(“\n address of structure’s element title %u “,&b1.title);
}
Output
cutting stone by Abraham is of Rs.400
address of structure’s element title 1700printf(“\n address of whole variable
%u”,&b1);
address of structure’s element author 1725
address of whole variable 4000
d) Size of a structure.
➢ When the sizeof operator is applied to an operand of a structure type it will
produce the result as how much memory space is occupied by that particular
object.
Syntax:
sizeof (expression);
sizeof type
Example:
sizeof (struct book); // use structure’s name
sizeof b1 // use variable
Program 2.7
#include<stdio.h>
struct book //structure type declaration
{
char a; // elements are declared
int b;
char c;
float d;
}; //structure type declarations are terminated
void main()
{
struct book var; //variable declaratio
printf(“obj of struct book will take %d bytes\n”,sizeof(struct book));
printf(“structure variable var takes %d bytes\n”, sizeof var);
}
Output:
obj of struct pad will take 8 bytes
structure variable var takes 8 bytes

2.2.2.2 Segregate Operations


➢ A segregate operation operates on the individual members of a structure object.
Program 2.8
#include<stdio.h>
struct book
{
char title[25], author[20];
int page; float price;
};
void main()
{
struct book b1;
printf(“enter title, author, page, price”);
scanf(“%s, %s, %d, %f”,& b1.title,&b1.author,&b1.page, &b1.price);
printf(“title is %s, author is %s, page no %d, price %d”,b1.title,
b1.author, b1.page, b1.price);
// operations on individual element
b1.page+=100;
b1.price+=10;
printf(“title is %s, author is %s, page no %d”,b1.title, b1.author,
b1.page);
printf(“price %d”,b1.price);
}
Output
Enter title, author, page, price
Principles of life, prabhu, 145, 200.00
Title is principles of life, author is prabhu, page no 145, price 200.00
Title is principles of life, author is prabhu, page no 245, price 210.00

2.3 UNION
➢ Union can be defined as a user-defined data type which is a collection of
different variables of different data types in the same memory location. The
union can also be defined as many members, but only one member can contain a
value at a particular point in time. Unions provide an efficient way of using the
same memory location for multiple-purpose.
➢ Union is a user-defined data type, but unlike structures, they share the same
memory location.
Defining a Union
➢ To define a union, you must use the union statement in the same way as 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];
➢ 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.
Example Program 2.9 Illustration of Union
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
void 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, "Charulatha publication");
printf( "data.str : %s\n", data.str);
}
Output
data.i : 10
data.f : 220.500000
data.str : Charulatha publication
Difference between Structure and Union
Sl.No Structure Union
1 The member of a structure occupies The member of union share same
its own memory space. memory space.
2 The keyword struct is used to define The keyword union is used to define a
a structure structure
3 All the members of a structure can Only the first member of a union can
be initialized. be initialized.
4 In structure, each member is stored In union, all members are stored in
in a separate memory location. So the same memory locations. So, need
need more memory space. less memory space.

2.4 POINTERS
2.4.1 Pointers to Variables
➢ A pointer is a variable that stores an address of another variable of same type.
➢ Pointer can have any name that is legal for other variable.
➢ Pointer variables are declared with prefix of ‘*’ operator.
➢ Using a pointer variable, we can access the value of another variable assigned to
it.
Syntax
data_type *pointer_name;
Example
int *a;
➢ variable *a can store the address of any integer type variable.
➢ A pointer is a variable whose value is also an address.
➢ Each variable has two attributes
✓ Value
✓ Address
We can define pointers in two ways.
i) First a pointer is a variable and assigns different values to a pointer variable.
ii) Second the value contained by a pointer must be an address which indicates the
location of another variable in the memory. So, pointer is called as “address
variable”.
Example
int a=50;
int *ptr;
ptr=&a;

➢ Here ‘a’ is a variable holds a value 50 and stored in a memory location 1001.
‘*ptr’ is pointer variable holds a address of a variable ‘a’.
Advantages of Using Pointers
➢ Pointers are more compact and efficient code.
➢ Pointers can be used to achieve clarity and simplicity.
➢ Pointers are used to pass information between function and its reference point.
➢ A pointer provides a way to return multiple data items from a function using its
function arguments.
➢ Pointers also provide an alternate way to access an array element.
➢ A pointer enables us to access the memory directly.
Example Program 2.10
/*C program for printing value and address of a variable using pointer variable*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *ptr;
ptr=&i;
clrscr();
printf(“Address of i=%u\n”,ptr);
printf(“value of i=%d\n”,*ptr);
getch();
}
Output:
Address of i=65524
value of i=3
Example Program 2.11
/*C program for printing value and address of a variable using pointer variable by
various methods*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=4;
int *j;
j=&i;
clrscr();
printf(“Address of i=%u\n”,&i);
printf(“Address of i=%u\n”,j);
printf(“Address of j=%u\n”,&j);
printf(“value of j=%u\n”,j);
printf(“value of i=%d\n”,i);
printf(“value of i=%d\n”,*(&i));
printf(“value of i=%d\n”,*j);
getch();
}
Output
Address of i=65524
Address of i=65524
Address of j=65522
value of j=65524
value of i=4
value of i=4
value of i=4
Example Program 2.12
/*C program to add two numbers using pointers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*p,*q,sum;
clrscr();
printf(“Enter two integers”);
scanf(“%d %d”,&a,&b);
p=&a;
q=&b;
sum=*p+*q;
printf(“sum=%d”,sum);
getch();
}
Output
Enter two integers 2 3
sum=5

2.4.2 Pointer operators


a) Referencing a pointer
➢ A pointer variable is made to refer to an object.
➢ Reference operator(&) is used for this.
➢ Reference operator is also known as address of (&) operator.
Example
float a=12.5;
float *p;
p=&a;
b) Dereferencing a pointer
• The object referenced by a pointer can be indirectly accessed by
dereferencing the pointer.
• Dereferencing operator (*) is used for this.
• This operator is also known as indirection operator or value- at-operator.
Example
int b;
int a=12;
a int *p;
Example program 2.13
#include<stdio.h>
void main()
{
int a=12;
int *p;
int **pptr;
p=&a;
pptr=&p;
printf(“Value=%d”,a);
printf(“value by dereferencing p is %d \n”,*p);
printf(“value by dereferencing pptr is %d \n”,**pptr);
printf(“value of p is %u \n”,p);
printf(“value of pptr is %u\n”,pptr);
}
Output
Value=12
value by dereferencing p is 12
value by dereferencing pptr is 12
value of p is 1000
2.4.3 Arrays and pointers
➢ Array elements are always stored in consecutive memory locations according to
the size of the array.
➢ The size of the variable with the pointer variables refers to, depends on the data
type pointed by the pointer.
➢ A pointer when incremented, always points to a location after skipping the
number of bytes required for the data type pointed to by it.
Example
int a[5]={10,20,30,40,50};
a[5] means the array ‘a’ has 5 elements and of integer data type
Program 2.14
/*C program to print the value and address of an array elements*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={10,20,30,40,50};
int i;
clrscr();
for(i=0;i<5;i++)
{
printf(“The value of a[%d]=%d\n”,i,a[i]);
printf(“Address of a[%d]=%u\n”,i,&a[i]);
}
getch();
}
Output
The value of a[0]=10
Address of a[0]=4000
The value of a[1]=20
Address of a[1]=4002
The value of a[2]=10
Address of a[2]=4004
The value of a[3]=10
Address of a[3]=4006
The value of a[4]=10
Address of a[4]=4008
Example Program 2.15
/*C program to print the value and address of an array elements using pointer*/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5]={10,20,30,40,50};
int i,*p;
p=arr;
clrscr();
for(i=0;i<=5;i++)
{
printf(“\nAddress=%u\t”,(p+i));
printf(“Element=%d”,*(p+i));
}
getch();
}
Output
Address 4000 Element=10
Address 4002 Element=20
Address 4004 Element=30
Address 4006 Element=40
Address 4008 Element=50
Example Program 2.16
/*C program to add sum of elements of an array using pointer*/
#include<stdio.h>
main()
{
int i,sum;
int arr[5];
int *ptr;
for(i=0;i<5;i++)
{
printf (“Enter the number”);
scanf(“%d”,&arr[i]);
}
ptr=arr;
for(i=0;i<5;i++)
{
sum=sum+*ptr
Functions and Pointers 3.29
ptr=ptr+1;
}
printf(“Total=%d”,sum);
}
Output
Enter the number
10
30
40
50
Total= 150

2.4.3.1 Pointers with Multi-Dimensional Array


➢ A multi-dimensional array can also be represented with an equivalent pointer
notation. A two dimensional array can be considered as a collection of one-
dimensional arrays.
Syntax
data_type (*pointer variable) [expression];
data_type array name[expression 1][expression 2];
Example Program 2.17
/*C program to print the value and address of the element using array of
pointers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int * int *a[3];
int b=10,c=20,d=30,i;
a[0]=&b;
a[1]=&c;
a[2]=&d;
clrscr();
for(i=0;i<3;i++)
{
printf(“Address=%u\n”,a[i]);
printf(“Value=%d\n”,*(a[i]));
getch();
}
Output
Address=4000
Value=10
Address=5000
Value=20
Address=6000
Value=30

2.4.4 Functions Pointers


➢ Function pointers in C can be used to create function calls to which they point.
This allows programmers to pass them to functions as arguments. Such
functions passed as an argument to other functions are also called callback
functions.
➢ In C programming, it is also possible to pass addresses as arguments to
functions. To accept these addresses in the function definition, we can use
pointers. It's because pointers are used to store addresses.
Example Program 2.18
Write a C Program for Swapping of two numbers using function pointers.
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Output
num1 = 10
num2 = 5
➢ The address of num1 and num2 are passed to the swap() function using
swap(&num1, &num2);
➢ When *n1 and *n2 are changed inside the swap() function, num1 and num2
inside the main() function are also changed.
➢ Inside the swap() function, *n1 and *n2 swapped. Hence, num1 and num2 are
also swapped.

2.5 ENUMERATED DATA TYPES


➢ Enumeration or Enum in C is a special kind of data type defined by the user. It
consists of constant integrals or integers that are given names by a user. The use of
enum in C to name the integer values makes the entire program easy to learn,
understand, and maintain by the same or even different programmer.
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.
Example
• Below is an example of an enum named cars and how you can change the
default values.
enum cars{BMW, Ferrari, Jeep, Mercedes-Benz};
o 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
};

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

2.5.2 Implementing enum using C Program


Example program 2.19: Printing the Values of Weekdays
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday};
// printing the values of weekdays
for(int i=Sunday;i<=Saturday;i++){
printf("%d, ",i);
}
return 0;
}
Output

2.6 FILE HANDLING


➢ A file is a collection of bytes stored on a secondary storage device, which is
generally a disk of some kind. The collection of bytes may be interpreted, for
example, as characters, words, lines, paragraphs and pages from a textual
document; fields and records belonging to a database; or pixels from a graphical
image.
➢ The meaning attached to a particular file is determined entirely by the data
structures and operations used by a program to process the file. It is conceivable
(and it sometimes happens) that a graphics file will be read and displayed by a
program designed to process textual data.
➢ The result is that no meaningful output occurs (probably) and this is to be
expected. A file is simply a machine decipherable storage media where
programs and data are stored for machine usage.

2.6.1 Why we need file?


➢ When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
➢ If you have to enter a large number of data, it will take a lot of time to enter
them all. However, if you have a file containing all the data, you can easily
access the contents of the file using few commands in C. It is possible easily
move your data from one computer to another without any changes.
2.6.2 File Operations
➢ In programming, we may require some specific input data to be generated
several numbers of times. Sometimes, it is not enough to only display the data
on the console. The data to be displayed may be very large, and only a limited
amount of data can be displayed on the console, and since the memory is
volatile, it is impossible to recover the programmatically generated data again
and again.
➢ However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in
C.
➢ 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

2.6.2.1 Types of Files


➢ There are two kinds of files in which data can be stored in two ways either in
characters coded in their ASCII character set or in binary format. They are
1. Text Files (or) ASCII file
2. Binary Files
Text Files (or) ASCII file
➢ The file that contains ASCII codes of data like digits, alphabets and symbols is
called text file (or) ASCII file.
Binary Files
➢ A binary file is a file that uses all 8 bits of a byte for storing the information .It is
the form which can be interpreted and understood by the computer.
➢ The only difference between the text file and binary file is the data contain in
text file can be recognized by the word processor while binary file data can’t be
1. wb(write)
This opens a binary file in write mode.
SYNTAX: fp=fopen(“data.dat”,”wb”);
2. rb(read)
This opens a binary file in read mode
SYNTAX:fp=fopen(“data.dat”,”rb”);
3. ab(append)
This opens a binary file in a Append mode i.e. data can be added at the end
of file.
SYNTAX: fp=fopen(“data.dat”,”ab”);
4. r+b(read+write)
This mode opens preexisting File in read and write mode.
SYNTAX: fp=fopen(“data.dat”,”r+b”);
5. w+b(write+read)
This mode creates a new file for reading and writing in Binary mode.
SYNTAX: fp=fopen(“data.dat”,”w+b”);
6. a+b(append+write)
This mode opens a file in append mode i.e. data can be written at the end of
file.
SYNTAX: fp=fopen(“data.dat”,”a+b”);
Opening Modes in Standard I/O
r Open for reading If the file does not exist, fopen() returns
NULL
rb Open for reading in binary If the file does not exist, fopen() returns
mode. NULL.
w Open for writing. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb Open for writing in binary If the file exists, its contents are overwritten.
mode. If the file does not exist, it will be created.
a Open for append. i.e, Data is If the file does not exists, it will be created.
added to the end of file.
ab Open for append in binary If the file does not exists, it will be created.
mode. i.e, Data is added to
end of file.
r+ Open for both reading and If the file does not exist, fopen() returns
writing. NULL.
rb+ Open for both reading and If the file does not exist, fopen() returns
writing in binary file. NULL
w+ Open for both reading and If the file exists, its contents are overwritten.
writing. If the file does not exist, it will be created.
wb+ Open for both reading and If the file exists, its contents are overwritten.
writing in binary mode. If the file does not exist, it will be created.
a+ Open for both reading and If the file does not exists, it will be created.
appending.
ab+ Open for both reading and If the file does not exists, it will be created.
appending in binary mode.

Closing a File: fclose(fptr);


➢ The file (both text and binary) should be closed after reading/writing. Closing a
file is performed using library function fclose().
Reading and writing to a text file
➢ The functions fprintf() and fscanf() are used to read or write the file They are
just the file versions of printf() and scanf(). The only difference is that, fprint
and fscanf expects a pointer to the structure FILE.
Writing to a text file
Program 2.20: Write to a text file using fprintf()
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen(“C:\\program.txt”,”w”);
if(fptr == NULL)
{
printf(“Error!”);
exit(1);
}
printf(“Enter num: “);
scanf(“%d”,&num);
fprintf(fptr,”%d”,num);
fclose(fptr);
return 0;
}
➢ This program takes a number from user and stores in the file program.txt. After
you compile and run this program, you can see a text file program.txt created in
C drive of your computer. When you open the file, you can see the integer you
entered.
Reading from a text file
Program 2.21: Read from a text file using fscanf()
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.txt”,”r”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,”%d”, &num);
printf(“Value of n=%d”, num);
fclose(fptr);
return 0;
}
Reading and writing to a binary file
➢ Functions fread() and fwrite() are used for reading from and writing to a file on
the disk respectively in case of binary files.
Writing to a binary file
➢ To write into a binary file, you need to use the function fwrite(). The functions
takes four arguments: Address of data to be written in disk, Size of data to be
written in disk, number of such type of data and pointer to the file where you
want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Program 2.22: Writing to a binary file using fwrite()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.bin”,”wb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
➢ We declare a structure three Num with three numbers - n1, n2 and n3, and
define it in the main function as num. Now, inside the for loop, we store the
value into the file using fwrite.
➢ The first parameter takes the address of num and the second parameter takes the
size of the structure three Num. Since, we’re only inserting one instance of num,
the third parameter is 1. And, the last parameter *fptr points to the file we’re
storing the data. Finally, we close the file.
Reading from a binary file
➢ Function fread() also take 4 arguments similar to fwrite() function as above.
fread(address_data,size_data,numbers_data,pointer_to_file);
Program 2.23: Reading from a binary file using fread()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.bin”,”rb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf(“n1: %d\tn2: %d\tn3: %d”, num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
➢ This program will start reading the records from the file program.bin in the
reverse order (last to first)
Text Files
➢ In C, all components are files, each with a different behavior based on the
attached devices. To enable the I/O functions, several standard built-in functions
were created and stored in libraries.
➢ Some of the high level file I/O functions are given in Table 2.1
Table 2.1 High level file I/O functions
S.No Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file

1. fopen () : It creates a new file for use or opens an existing file for use.
2. fclose (): It closes a file which has been opened for use.
3. fscanf( file pointer, format string, address of the variable)
Example: fscanf(fptr,”%d”, &num);
4. fprintf(console output, “format string”, file pointer);
Example: fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
5. getw (): This function returns the integer value from a given file and increment the
file pointer position to the next message.
Syntax: getw (fptr);
Where fptr is a file pointer which takes the integer value from file.
6. putw (): This function is used for writing an integer value to a given file.
Syntax: putw (value,fptr);
Where fptr is a file pointer Value is an integer value which is written to a given file.
Example Program for getw() and putw()
Program 2.24: Write a program to read integer data from the user and write it
into the file using putw() and read the same integer data from the file using getw()
and display it on the output screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int n;
clrscr();
fp=fopen(“c.dat”, “wb+”);
printf(“Enter the integer data”);
scanf(“%d”,&n);
while(n!=0)
{
putw(n,fp);
scanf(“%d”,&n);
}
rewind(fp);
printf(“Reading data from file”);
while((n=getw(fp))!=EOF)
{
printf(“%d\n”,n);
}
fclose(fp);
getch();
}
7. fwrite()
➢ This function is used for writing an entire block to a given file.
Syntax: fwrite(ptr,size,nst,fptr);
ptr is a pointer ,it points to the array of structure.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.
8. fread()
➢ fread(ptr,size,position,fptr);similar to fwrite
Program 2.25: program for fwrite():
Write a program to read an employee details and write them into the file at a time
using fwrite().
#include<stdio.h>
#include<conio.h>
void main()
{
struct emp
{
int eno;
char ename[20];
float sal;
}e;
FILE *fp;
fp=fopen(“emp.dat”, “wb”);
clrscr();
printf(“Enter employee number”);
scanf(“&d”,&e.eno);
printf(“Enter employee name”);
fflush(stdin);
scanf(“%s”,e.ename);
printf(“Enter employee salary”);
scanf(“%f”,&e.sal);
fwrite(&e,sizeof(e),1,fp);
printf(“One record stored successfully”);
getch();
}
Operations for Search data in a file
1. fseek()
2. ftell()
3. rewind()
fseek() : Getting data using fseek()
➢ When many records inside a file and need to access a record at a specific
position, you need to loop through all the records before it to get the record. This
will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek().
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)
fseek(file pointer, displacement, pointer position);
➢ he first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.
➢ This function is used for seeking the pointer position in the file at the specified
byte.
Syntax: fseek( file pointer, displacement, pointer position);
file pointer - It is the pointer which points to the file.
displacement -It is positive or negative.
➢ This is the number of bytes which are skipped backward (if negative) or forward
(if positive) from the current position. This is attached with L because this is a
long integer.
Pointer position: This sets the pointer position in the file.
Value Pointer position Value Pointer position
0 Beginning of file.
1 Current position
2 End of file

Example:
1. fseek( p,10L,0)
➢ This 0 means pointer position is on beginning of the file, from this statement
pointer position is skipped 10 bytes from the beginning of the file.
2. fseek( p,5L,1)
➢ This 1 means current position of the pointer position. From this statement
pointer position is skipped 5 bytes forward from the current position.
3. fseek(p,-5L,1):
➢ From this statement pointer position is skipped 5 bytes backward from the
current position.

Program 2.26: for fseek()


#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.bin”,”rb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
fseek(fptr, sizeof(struct threeNum), SEEK_END);
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf(“n1: %d\tn2: %d\tn3: %d”, num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
ftell()
➢ This function is used to move the file pointer to the beginning of the given file.
This function returns the value of the current pointer position in the file. The
value is count from the beginning of the file.
Syntax: ftell(fptr); fptr is a file pointer.
rewind()
Syntax: rewind( fptr); fptr is a file pointer.
Program 2.27: program for fseek():
Write a program to read last ‘n’ characters of the file using appropriate file
functions(Here we need fseek() and fgetc()).
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen(“file1.c”, “r”);
if(fp==NULL)
printf(“file cannot be opened”);
else
{
printf(“Enter value of n to read last ‘n’ characters”);
scanf(“%d”,&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf(“%c\t”,ch);
}
}
fclose(fp);
getch();
}

2.7 PREPROCESSOR DIRECTIVES


➢ The C preprocessor is a microprocessor that is used by compiler to transform
your code before compilation. It is called micro preprocessor because it allows
us to add macros.
➢ Note: A macro is a segment of code which is replaced by the value of macro.
Macro is defined by #define directive.
Example
#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
➢ All preprocessor directives starts with hash # symbol. Let's see a list of
preprocessor directives.
• #define: It substitutes a preprocessor using macro.
• #include: It helps to insert a certain header from another file.
• #undef: It undefines a certain preprocessor macro.
• #ifdef: It returns true if a certain macro is defined.
• #ifndef: It returns true if a certain macro is not defined.
• #if, #elif, #else, and #endif: It tests the program using a certain condition;
these directives can be nested too.
• #line: It handles the line numbers on the errors and warnings. It can be used
to change the line number and source files while generating output during
compile time.
• #error and #warning: It can be used for generating errors and warnings.
• #error can be performed to stop compilation.
• #warning is performed to continue compilation with messages in the console
window.
• #region and #endregion: To define the sections of the code to make them
more understandable and readable, we can use the region using expansion
and collapse features.
REVIEW QUESTIONS
PART A
1. What is a Structure in C?
➢ Structure is a user-defined datatype in C language which allows us to combine
data of different types together. Structure helps to construct a complex data type
which is more meaningful.
➢ In structure, data is stored in form of records.
2. How to define a Structure?
➢ struct keyword is used to define a structure. struct defines a new data type
which is a collection of primary and derived data types.
➢ Syntax
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
3. What is Union?
➢ 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.
4. Give the syntax for creating a union.
union [union name]
{
member definition;
member definition;
...
member definition;
};
5. Difference between Structure and Union.
Structure Union
The Keyword struct is used to define The Keyword union is used to define
the Structure the Union
Structure allocates storage space for all Union allocates one storage space for
its members seperately. all its members.
Structure occupies high memory space Union occupies low memory space
when compared to Structure
We can access all members of Only one member of union can be
Structure at a time accessed at a time.
Altering the value of a member will Altering the value of a member will
not affect other member of a structure alter other member value in union.

6. What are Enumerated Datatypes?


➢ Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and
maintain.
7. What is pointer?
➢ A pointer is a variable that stores the memory address of another variable as its
value. A pointer variable points to a data type (like int) of the same type and is
created with the * operator.
8. How addresses are assigned to Pointers?
➢ Example
int* p, a;
a= 8;
p = &a;
➢ Here, 8 is assigned to the variable a and the address of a is assigned to the
pointer p.
9. What are the uses of Pointers?
➢ Pointers are used to return more than one value to the function
➢ Pointers are more efficient in handling the data in arrays
➢ Pointers reduce the length and complexity of the program
➢ They increase the execution speed
➢ The pointers saves data storage space in memory.
10. What is the difference between an array and pointer?
Arrays Pointers
Array allocates space automatically. Pointer is explicitly assigned to point
to an allocated space.
It cannot be resized. It can be resized using realloc ().
It cannot be reassigned. Pointers can be reassigned.
Sizeof(array name) gives the number Sizeof(pointer name) returns the
of bytes occupied by the array. number of bytes used to store the
pointer variable.

11. What is dangling pointer?


➢ In C, a pointer may be used to hold the address of dynamically allocated
memory. After this memory is freed with the free() function, the pointer itself
will still contain the address of the released block. This is referred to as a
dangling pointer.
➢ Using the pointer in this state is a serious programming error. Pointer should be
assigned NULL after freeing memory to avoid this bug.
12. What is ‘C’ functions?
➢ A function is a self-contained block (or) a sub-program of one or more
statements that performs a special task when called.
➢ To perform a task repetitively then it is not necessary to re-write the particular
block of the program again and again. The function defined can be used for any
number of times to perform the task.
13. Differentiate library functions and User-defined functions.
Library Functions User-defined Functions
The User-defined functions are the
Library functions are pre-defined set of functions defined by the user according
functions that are defined in C libraries. to his/her requirement.

User can only use the function but User can use this type of function.
cannot change (or) modify this function. User can also modify this function.

14. What are the steps in writing a function in a program?


➢ Function Declaration (Prototype declaration): Every user-defined function has to
be declared before the main().
➢ Function Calling: The user-defined functions can be called inside any functions
like main(), user-defined function, etc.
➢ Function Definition: The function definition block is used to define the user-
defined functions with statements.
15. What is a use of ‘return’ Keyword?
➢ The ‘return’ Keyword is used only when a function returns a value.
16. What is the purpose of the function main()?
➢ The function main () invokes other functions within it. It is the first function to
be called when the program starts execution.
➢ Features of Main method
o It is the starting function.
o It returns an int value to the environment that called the program.
o Recursive call is allowed for main () also.
o It is a user-defined function.
o Program execution ends when the closing brace of the function main() is
reached.
o It has two arguments (a) argument count and (b)argument vector (represents
strings passed.)
17. Compare between Array and Structure
Arrays Structures
An array is a collection of data items A structure is a collection of data items
of same data type. of different data types.
Arrays can only be declared. There is Structures can be declared and defined.
no keyword for arrays. The Keyword for structures is struct.
An array name represents the address A structure name is known as tag. It is a
of the starting element. shorthand notation of the declaration.
An array cannot have bit fields. A structure may contain bit fields.

18. Is it better to use a macro or a function?


➢ Macros are more efficient (and faster) than function because their corresponding
code is inserted directly at the point where the macro is called. There is no
overhead involved in using a macro like there is in placing a call to a function.
➢ However, macros are generally small and cannot handle large, complex coding
constructs. In cases where large, complex constructs are to handled, functions
are more suited, additionally; macros are expanded inline, which means that the
code is replicated for each occurrence of a macro.
19. List the characteristics of Arrays.
➢ All elements of an array share the same name, and they are distinguished form
one another with help of an element number.
➢ Any element of an array can be modified separately without disturbing other
elements.
20. What are the types of Arrays?
➢ One-Dimensional Array
➢ Two-Dimensional Array
➢ Multi-Dimensional Array
21. What is File Handling in C?
➢ A file is nothing but a source of storing information permanently in the form of a
sequence of bytes on a disk. The contents of a file are not volatile like the C
compiler memory. The various operations available like creating a file, opening
a file, reading a file, or manipulating data inside a file is referred to as file
22. What is the need for File Handling in C?
➢ Reusability: It helps in preserving the data or information generated after
running the program.
➢ Large storage capacity: Using files, you need not worry about the problem of
storing data in bulk.
➢ Saves time: There are certain programs that require a lot of input from the user.
You can easily access any part of the code with the help of certain commands.
➢ Portability: You can easily transfer the contents of a file from one computer
system to another without having to worry about the loss of data.
23. List some of C File Handling Operations.
➢ Creating a new file: fopen()
➢ Opening an existing file in your system: fopen()
➢ Closing a file: fclose()
➢ Reading characters from a line: getc()
➢ Writing characters in a file: putc()
➢ Reading a set of data from a file: fscanf()
➢ Writing a set of data in a file: fprintf()
➢ Reading an integral value from a file: getw()
24. Give the syntax for Opening a Text File in C.
Syntax
*fpointer = FILE *fopen(const char *file_name, const char *mode);
• *fpointer is the pointer to the file that establishes a connection between the
file and the program.
• *file_name is the name of the file.
• *mode is the mode in which we want to open our file.
25. How to Read and Write a Text File in C?
➢ The input/output operations in a file help you read and write in a file.
➢ The simplest functions used while performing operations on reading and writing
characters in a file are getc() and putc() respectively.
➢ In order to read and write a set of data in a file, we use the fscanf() and fprintf()
operators.
26. Write short notes on Preprocessor Directives.
➢ The C preprocessor is a macro processor that is used automatically by the C
compiler to transform your program before actual compilation (Preprocessor
directives are executed before compilation.).
➢ It is called a macro processor because it allows you to define macros, which are
brief abbreviations for longer constructs.
27. What is macro?
➢ A macro is a segment of code which is replaced by the value of macro. Macro is
defined by #define directive.
28. List few preprocessor directives in C.
➢ #include
➢ Macro's (#define)
➢ #undef
➢ #ifdef
➢ #ifndef
➢ #if
➢ #else
PART-B

1. Explain Structure in C with neat program.


2. Write short notes on Union with example program.
3. What is a function? Explain with neat program.
4. Explain call by value and call by reference with example programs.
5. Explain the file handling mechanism in C with programs.
6. Explain preprocessor directives with its types and examples.
7. Explain the concept of pointers with neat programs.
8. Write shorts notes on Arrays.
9. How to write Data into a text file and Read Data from the file? Discuss.
10. How to read and write data to the binary file in a program? Explain.

You might also like