You are on page 1of 26

CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

UNIT- II
C PROGRAMMING - ADVANCED FEATURES
Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays and Functions
– File Handling – Preprocessor Directives.
STRUCTURE:
 A Structure is a collection of different data types that are stored under a common name.
 It is a user-defined data type.
Syntax:
struct tag_name
{
datatype element_1;
datatype element_2;

datatype element_n;
} variable_1, variable_2, variable_3;
 struct is a keyword, which declares a structure.
 tag_name is called as, the name of a structure.
 datatype element_1, datatype element_2 and so on are called as structure members which is of
different data types.
 variable_1, variable_2, .., variable_n are called as structure variables.
 Only by using this structure variables we can access the structure members.
Example:
struct student
{ // structure template
int rollno;
char name[100];
char address[100];
}s1,s2,s3; // structure declaration
FEATURES OF STRUCTURES:
1.The structure elements are stored in successive memory locations.
2.Nesting of structure is possible.
3.It is also possible pass structure elements to a function.
4.One can pass individual structure as a function argument by value or address.
NEED FOR STRUCTURE DATA TYPE:
1.Structure in C allows us to combine different data types to store a particular type of record.
2.Structure helps to construct a complex data type in more meaningful way.
3.It is somewhat similar to an Array. The only difference is that array is used to store collection of similar
data types while structure can store collection of different data types.
4.Structure is used to represent a record. Suppose you want to store record of Student which consists of
student name, address, roll number and age. we can define a structure to hold this information.
Structure Declaration:
struct book
{
char title[10];
int pages;
float price;
};

1
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

struct book bk; // structure declaration


 A structure book is created , it contains of three members title, pages, price.
 Variable “bk” of type book and it reserves a total of 16 bytes .
 Through bk, all the three elements of structure can be accessed with certain values.
INITIALIZING AND ACCESSING STRUCTURE ELEMENTS:
Example struct book bk={“Computer”,500,150.00}; …………………..// Initialization
bk.title=”computer”,bk.pages=500,bk.price=150.00……..//Initialization of each member separately.
Program:
#include<stdio.h>
struct book
{
char title[10];
int pages;
float price;
};
void main()
{
struct book bk;
printf(“Enter Book Name);
scanf(“%s”,&bk.title);
printf(“Enter No.Of.Pages ”);
scanf(“%d”,&bk.pages);
printf(“Enter price”);
scanf(“%f”,&bk.price);
printf(“Book Name =%s”,bk.title); …………………..// Accessing structure elements
printf(“Book pages =%d”,bk.pages);
printf(“Book price=%f”,bk.price);
getch();
}
Output:
Enter Book Name C-Book
Enter No.Of.Pages 280
Enter price 140.50
Book Name = C-Book
Book pages = 280
Book price= 140.50
STRUCTURE WITHIN STRUCTURE:
 Structure written inside another structure is called as Structure within structure. It is also called as nested
Structures .
Example:
struct student
{
char name[20];
int age;
struct address
{
char streetname[20];

2
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

char city[20];
int pincode;
}
};
Example program for employee details using structure
#include<stdio.h>
struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};
struct Employee
{
int IdNo;
char Name[25];
float Salary;
struct Address Add;
};
void main()
{
int i;
struct Employee E;
printf("\n\tEnter Employee Id : ");
scanf("%d",&E.IdNo);
printf("\n\tEnter Employee Name : ");
scanf("%s",&E.Name);
printf("\n\tEnter Employee Salary : ");
scanf("%f",&E.Salary);
printf("\n\tEnter Employee House No : ");
scanf("%s",&E.Add.HouseNo);
printf("\n\tEnter Employee City : ");
scanf("%s",&E.Add.City);
printf("\n\tEnter Employee House No : ");
scanf("%s",&E.Add.PinCode);
printf("\nDetails of Employees");
printf("\n\tEmployee IdNo : %d",E.IdNo);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployee House No : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployee House No : %s",E.Add.PinCode);
}
Output :
Enter Employee IdNo : 101
Enter Employee Name : Suresh
Enter Employee Salary : 45000

3
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

Enter Employee House No : 4598/D


Enter Employee City : Delhi
Enter Employee Pin Code : 110056
Details of Employees
Employee IdNo : 101
Employee Name : Suresh
Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi
Employee Pin Code : 110056
ARRAY OF STRUCTURE:
 Array is a collection of similar data types. It also define array of structure type.
Example
struct student
{
int stu_age;
}stu[5];
 stu[5] is an array of 5 elements containing five objects of student structure.
 Each element of stu[5] has a structure with stu_age member.
Example
#include<stdio.h>
main()
{
struct stu
{
char name[20];
int age;
}stu[10];
int i;
for(i=0;i<10;i++)
{
printf(“Enter the data of %d student\n”,i+1);
printf(“Name:”);
scanf(“%s”,stu[i].name);
printf(“\nAge:”);
scanf(“%d”,&stu[i].age);
}
printf (“\nName \t age \n”);
for(i=0;i<10;i++)
{
printf(“%s”,stu[i].name);
printf(“%d”,stu[i].age);
}
}
MARK SHEEET OF ‘N’ STUDENTS (or) STUDENT DETAILS USING STRUCTURE
#include<stdio.h>
#include<conio.h>

4
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

struct student
{
char name[10][10];
int rollno,m1,m2,m3,total;
};
void main()
{
int num,i,j;
struct student s1[10];
clrscr();
printf("enter the number of students\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
printf("enter the rollno");
scanf("%d",&s1[i].rollno);
printf("enter the name");
scanf("%s",s1[i].name);
printf("enter the mark1");
scanf("%d",&s1[i].m1);
printf("enter the mark2");
scanf("%d",&s1[i].m2);
printf("enter the mark3");
scanf("%d",&s1[i].m3);
s1[i].total=s1[i].m1+s1[i].m2+s1[i].m3;
}
printf("\n the details of the mark list is as follows\n");
printf("\n Roll no");
printf("\t Name");
printf("\t Mark 1");
printf("\t Mark 2");
printf("\t Mark 3");
printf("\t Total");
printf("\n");
for(i=0;i<num;i++)
{
printf("\n%d",s1[i].rollno);
printf("\t%s",s1[i].name);
printf("\t%d",s1[i].m1);
printf("\t%d",s1[i].m2);
printf("\t%d",s1[i].m3);
s1[i].total=s1[i].m1+s1[i].m2+s1[i].m3;
printf("\t%d",s1[i].total);
}
getch();
}

5
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

Output:
Enter the Number of students: 2
Enter the Roll number : 01
Enter the Name : Raja
Enter the Mark1 : 98
Enter the Mark1 : 95
Enter the Mark1 : 85

Enter the Roll number : 02


Enter the Name : Roja
Enter the Mark1 : 81
Enter the Mark1 : 75
Enter the Mark1 : 90

The Details of the Mark list is as follows

Roll No Name Mark1 Mark2 Mark3 Total


01 Raja 98 95 85 278
02 Roja 81 75 90 246
UNION:
An Union is a collection of different data items, that are stored under a common name. Here same memory
is shared by its members.
Syntax:
union union_name
{
data-type element1;
data-type element2;
data-type element3;
}union_variable;
Example:
union result
{
int mark;
char grade;
float avg;

}s;
1. In above example, it declares “s” variable of type union.
2. The union contains three members as data type of int, char, float.
3. We can use only one of them at a time.
Memory allocation :

Fig : Memory allocation for union

6
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

ACCESSING A UNION MEMBER:


To access union members, we can use the following syntax.
Unionvariable. Element
Example:
s.mark
s.grade
s.avg
Example program for employee details using Union
#include<stdio.h>
#include<conio.h>
union employee
{
char name[25];
int empno;
int bpay;
float netpay;
}emp[20];

void main()
{
int num,i,da=5,pf=1500;
clrscr();
printf("Enter the no of the Employee \n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
printf("\n enter the employee number");
scanf("%d",&emp[i].empno);
printf("\n the employee number : %d",emp[i].empno);
printf("\n enter the employee name");
scanf("%s",&emp[i].name);
printf("\nthe employee name :%s",emp[i].name);
printf("\n enter the basic pay");
scanf("%d",&emp[i].bpay);
printf("the basic pay:%d",emp[i].bpay);
emp[i].netpay= emp[i].bpay +(emp[i].bpay*da/100)-pf;
printf("the net pay:%f",emp[i].netpay);
}
}
POINTER TO STRUCTURE:
 Variable may be of any datatype like int,float,double.
 We can define pointer to structure. Here starting address of the member variable can be accessed.
Ex :
Struct book
{
Char name[25];
Char author[25];
7
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

Int pages;
};
Struct book *ptr;
Here *ptr is pointer to structure book. 1. Ptr->name 2.ptr->author 3. Ptr->pages.
Write a program to declare pointer to structure and display the contents of the structure.
void main()
{
struct book
{
char name[25];
char author[25];
int pages;
};
struct book b1={“c programming”,”ashok”,500};
struct book *ptr;
ptr=&b1;
clrscr();
printf(“%s by %s of %d pages”,b1.name,b1.author,b1.pages);
printf(“%s by %s of %d pages”,ptr->name,ptr->author,ptr->pages);
getch();
}
STRUCTURE AND FUNCTION :
 Structure variables can be passed to the function by value or address
 Structure element is to be passed to any other function it is essential to declare the structure outside the
main() function that is global structure. They can accessed by all other functions.
Ex:
struct book
{
char name[25];
char author[25];
int pages;
};
void main()
{
struct book b1={“c programming”,”ashok”,500};
show(&b1);
getch();
}
show(struct book *b2)
{
Clrscr();
Printf(“%s by %s of %d pages”,b2->name,b2->author,b2->pages);
}
POINTERS:
 A pointer is a memory variable that stores a memory address of another variable.
 Pointer variable is denoted by prefixing ‘*’ (asterisk) operator.
Eg: int *ptr.
8
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

POINTER DECLARATION AND INITIALIZATION:


 Pointer variables are declared with a prefix ‘*’,
 ‘*’ symbol is called as indirection operator and it is also called as dereferencing operator.
 ‘*’ symbol is used in two ways for declaring pointer variable and for dereferencing
Example program
void main( )
{
int x=10, int *ptr;
ptr = &x;
printf(“The value of x=%d”, x);
printf(“The value of ptr = %u”, ptr);
printf(“The address of x = %u”, &x);
printf(“The address of ptr = %u”,&ptr);
printf(“The pointer value of ptr = %d”, *ptr);
}

 In the above program ‘ptr’ is a pointer variable that holds the address of the variable ‘x’
 ‘&’ operator will give the address of a particular variable.
 ‘*ptr’ will retrieve the value of the address it holds, that why it is called as dereferencing operator.
USES OF POINTERS:
 Pointers save memory space.
 Execution time with the pointer is faster.
 The memory is accessed efficiently with pointers.
 Dynamic memory allocation is possible using pointers
 Pointers are used with data structures.
 Pointers are used in the file handling.
Write a program to add two numbers through variables and their pointers.
void main()
{
inta,b,c,d,*ap,*bp;
printf(“enter the 2 number”);
scanf(“%d %d”,&a,&b);
ap=&a;
bp=&b;
c=a+b;
d=*ap+*bp;
printf(“the sum of a,b using value =%d”,c);
pintf(“the sum of a,b using pointer %d”,d);
}

9
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

POINTERS AND ARRAYS:


 Array name by itself is an address or pointer, it points to the address of the first element of an array.
 The base address of array is the address of the 0’th element of the array.
 The name of array also gives the base address of the array.
Ex :
int arr[4]={5,10,15,20}; arr[0] arr[1] arr[2] arr[3]
int *a; 5 10 15 20
a=arr; or a=&arr[0]; 1000 1002 1004 1006
( a is a pointer variable which holds the base address a a+1 a+2 a+3 of the
array arr )
void main()
{
int arr[4]={5,10,15,20};
int *a;
a=&arr[0];
for (i=0;i<4;i++)
{
printf( “ value of arr[%d] = %d”,i,*a);
printf(“address of arr[%d]=%u”,i,a);
}
Output:
value of arr[0] = 5
address of arr[0]=1000
value of arr[1] = 10
address of arr[1]=1002
value of arr[2] = 15
address of arr[2]=1004
value of arr[3] = 20
address of arr[3]=1006
ARRAY OF POINTERS:
 This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an
int value. Following example makes use of three integers, which will be stored in an array of pointers as
follows
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[ ] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}

10
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

return 0;
}
Output
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
FUNCTION AND POINTERS:
Write the example program of call by reference page no: unit I - 32
POINTER TO POINTER:
 The pointer is known as a variable containing address of another variable.
 The pointer variable containing address of another pointer variable is known as pointer to pointer. The
chain can be continued to any extend.

 ‘p1′ that points to yet another pointer ‘p2′ that points to a character ‘ch’. In memory, the three variables
can be visualized.
 So we can see that in memory, pointer p1 holds the address of pointer p2. Pointer p2 holds the address of
character ‘ch’.
 So ‘p2′ is pointer to character ‘ch’, while ‘p1′ is pointer to ‘p2′ or we can also say that ‘p2′ is a pointer to
pointer to character ‘ch’.
 Now, in code ‘p2′ can be declared as : char *p2 = &ch;
 But ‘p1′ is declared as : char **p1 = &p2;
 So we see that ‘p1′ is a double pointer (ie pointer to a pointer to a character) and hence the two *’s are
used in declaration.
Example program
void main()
{
int a=2,*p,**q;
p=&a;
q=&p;
clrscr();
printf(“value a= %d address of a=%u”,a,&a);
printf(“value of *p=%d address of *p=%u”,*p,p);
printf(“value of**q=%d address of q=%u”,**q,*q);
}
POINTER AND STRINGS :
 A string is collection of characters that are stored in the character array. Every string is terminated with the
‘\0’(null character end of every string)
Ex :
Char arr[ ] = { ‘a’,’a’,’m’,’e’,’c’,’\0’};
void main()
{

11
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

charstr[20],*s;
int p=0,q=0;
clrscr();
printf(“enter string”);
gets(str);
s=str;
while (*s!=’\0’)
{
printf(“%c”,*s);
p++;
s++;
if (*s = = 32)
q++;
}
printf(“length of string including space = %d “,p);
printf(“length of string excluding space=%d”,p-q);
}
VOID POINTERS:
1.In C General Purpose Pointer is Called as void Pointer.
2.It does not have any data type associated with it
3.It can store address of any type of variable
4.A void pointer is a C convention for a raw address.
5.The compiler has no idea what type of object a void Pointer “really points to.” ?
Declaration of Void Pointer :
void * pointer_name;
Void Pointer Example :
void*ptr;// ptr is declared as Void pointer
charcnum;
intinum;
floatfnum;
ptr=&cnum;// ptr has address of character data
ptr=&inum;// ptr has address of integer data
ptr=&fnum;// ptr has address of float data
Explanation :
void*ptr;
 We have declared 3 variables of integer, character and float type.
 When we assign address of integer to the void pointer, pointer will become Integer Pointer.
 When we assign address of Character Data type to void pointer it will become Character Pointer.
 Similarly we can assign address of any data type to the void pointer.
 It is capable of storing address of any data type
ENUMERATED DATA TYPE:
 The enumerated data type is a user-defined type based on the standard integer type.
 An enumeration consists of a set of named integer constants.
 Each integer value is assigned an identifier.

12
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

 This identifier (which is also known as an enumeration constant) can be used as a symbolic name to make
the program more readable.
 Enumerations create new data types to contain values that are not limited to the values that fundamental
data types may take.
Syntax:
enum enumeration_name { identifier1, identifier2 , , ...identifiern };
 The enum keyword is basically used to declare and initialize a sequence of integer constants.
 Here, enumeration_ name is optional.
Example:
Creates a new type of variable called COLORS to store colour constants.
enum COLORS {RED, BLUE,BLACK,GREEN,YELLOW,PURPLE,WHITE};
 In case you do not assign any value to a constant , the default value of RED is 0, BLUE is 1, BLACK is
2, and so on.
 However, you can also change these default values while declaring the enum.
#include<stdio.h>
int main( )
{
enum {RED=2, BLUE,BLACK=5,GREEN=7,YELLOW,PURPLE,WHITE=15};
printf("\n RED = %d", RED);
printf("\n BLUE = %d", BLUE);
printf("\n BLACK =%d", BLACK);
printf("\n GREEN = %d”, GREEN);
printf("\n YELLOW=%d", YELLOW);
printf("\n PURPLE = %d", PURPLE);
printf('\n WHITE=%d", WHITE);
return 0;
}
Output:
RED = 2
BLUE = 3
BLACK = 5
GREEN = 7
YELLOW = 8
PURPLE = 9
WHITE = 15
RULES APPLY TO THE MEMBERS OF AN ENUMERATION LIST:
 An enumeration list may contain duplicate constant values.
 Therefore, two different identifiers may be assigned the same value, say 3.
 The identifiers in the enumeration list must be different from other identifiers in the same scope with the
same visibility including ordinary variable names and identifiers in other enumeration lists.
 Enumeration names follow the normal scoping rules. So every enumeration name must be different from
other enumeration, structure, and union names with the same visibility.
Anonymous enumerated type:
 If we create an enumerated type without enumeration_name, it is known as an anonymous enumerated
type.
Example: enum {OFF, ON};

13
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

declares an enumerated type that has two constants OFF with a value 0 and ON with a value 1.
enum Variables:
 We have seen that enumerated constants are basically integers, so programs with statements such as int
fore_color = RED; is considered to be a legal statement in C .
 In extension to this, C also permits the user to declare variables of an enumerated data type in the same
way as we create variables of other basic data types.
Syntax:
enumeration_name variable_name;
 So to create a variable of COLORS, we may write
enum COLORS bg_color;
 This declares a variable called bg_ color, which is of the enumerated data type, COLORS.
 Another way to declare a variable can be as illustrated in the following statement.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE} bg_color , fore_color;
Using the typedef keyword:
Example: If we write,
typedef enum COLORS color;
 Then we can straightaway declare variables by writing
Color forecolor = RED;
ASSIGNING VALUES TO ENUMERATED DATATYPE:
 Once the enumerated variable has been declared, values can be stored in it.
 However ,an enumerated variable can hold only declared values for the type.
Example, to assign the colour black to the background color, we will
bg_color = BLACK;
 Note that once an enumerated variable has been assigned a value, we can store its value in another variable
of the same type.
. Example:
enum COLORS bg_color , border_color;
bg_color = BLACK;
border_color = bg_color;
ENUMERATION TYPE CONVERSION:
 Enumerated types can be implicitly or explicitly cast.
 For example, the compiler can implicitly cast an enumerated type to an integer when required.
 However, when we implicitly cast an integer to an enumerated type, the compiler will either generate an
error or a warning message.
 To remove the error, you can do either of two things.
 First, declare c to be an int.
 Second, cast the right-hand side in the following manner.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
enum COLORS c;
c = BLACK ; // valid in C
c = 2 ; // illegal in C
c = ( enum COLORS ) 2 ; // Right way
COMPARING ENUMERATED TYPES:
 C also allows using comparison operators on enumerated data type.
bg_color = (enum COLORS)6;
if(bg_color == WHITE)

14
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

fore_color = BLUE;
fore_color = BLACK;
if(bg_color == fore_color)
printf (“\n NOT VISIBLE “ ) ;
 Since enumerated types are derived from integer type, they can be used in a switch case statement.
Example:
enum {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE}bg_color;
switch (bg_color)
case RED:·
case BLUE:
case GREEN:
printf("\n It is a primary color" );
break;
case default:
printf("\n It is not a primary color");
break;
}
Input/Output Operations on Enumerated Types:
 Since enumerated types are derived types, they cannot be read or written using formatted input/output
functions available in the C language.
 When we read or write an enumerated type, we read/write it as an integer.
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
enum COLORS c;
scanf (“ %d”, &c);
printf (“\n Color = %d”,c);
PREPROCESSOR DIRECTIVES:
 The preprocessor is a program that process the source program before it is passed to the compiler.
 It starts with # (symbol) before main() function and there is no semicolon with end.
 The program typed in the editor is the source code to the preprocessor.
 It is passed to the compiler.
 Preprocessor can reduce the execution time of a program
1. #define Directive (or MACRO)
It is used to define some constants
• Syntax
# define identifier string/integer
• Example:
#define pi 3.14
#define CITY “chennai”
 PI as macro template and 3.14 as macro substitute.
 Macro templates are generally declared with capital letter, it can also small letters.
 Identifiers are not a keyword can use valid variables.
Example1: Example2:
#include<stdio.h> #define PI 3.14
#include<conio.h> #define max 2
#define pi 3.14 #define cls clrscr()
#define CITY "chennai" #define display printf()

15
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

void main() void main()


{ {
printf("The Value is %f",2*pi); int k,r=3;
printf("\nThe Value CITY is %s",CITY); cls;
getch(); for(k=1;k<=max;k++)
} {
Output: display(“%d”,pi*r*r);
The Value is 6.280000 }
The Value CITY is chennai Output:
28.26
28.26
2. #include Directive (or File Inclusion)
It is used to include some file that contains functions or some definitions
 The # include directive loads specified file in the current program.
 The macros and functions of loaded file can be called in the current program.
 The included file also gets compiler with the current program
Syntax
#include<filename> (or)
#include“filename”
Example:
#include <stdio.h>
#include “conio.h”
#include “sample.h”
3. Conditional compilation:
• It is used to include some conditional statements.
 #ifdef, #else, #endif are conditional compilation.
 The programmer used for code based condition applied for source code.
 The compiler compiles the selected portions.
a) #ifdef and #ifndef
#ifdef – Checks the portion true and false block
#ifndef - Opposite of #ifdef (negative).
Example-ifdef Example-ifndef
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
#define a 3 #define a 3
#ifdef a #ifndef b
#define c a+5 #define b 5
#endif #endif
void main() void main()
{ {
printf("\nThe value C is %d",c); printf("\nThe value B is %d",b);
getch(); getch();
} }
Output:The value C is 8 Output:The value B is 5
4. #error Directive:
 It is used to display user defined message during compilation of the program.
#define B 1
16
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

void main()
{
clrscr();
#if defined (a)
printf(“macro found”);
#else
#error macro is not defined
#endif
}
FILE HANDLING IN C:
 Real life situations involve large volume of data and in such cases, the console oriented I/O operations
pose two major problems.
 It becomes cumbersome and time consuming to handle large volumes of data through terminals.
 The entire data is lost when either the program is terminated or computer is turned off therefore it is
necessary to have more flexible approach where data can be stored on the disks and read whenever
necessary, without destroying the data. This method employs the concept of files to store data.
 File is defined as a set of records, containing numbers, symbols and text that can be accessed through
various file functions.
 There are two types of files namely, sequential file and random access file.
 In sequential access file systems, records are stored in sequential manner.
 To access the nth record, all the records starting from 0 to n-1 need to be accessed.
 In random access file system, a record can be read and modified at random.
 C supports a number of functions that have the ability to perform basic file operations, which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
File operation functions in C:
Function Name Operation
Creates a new file for use
fopen ( )
Opens a new existing file for use
fclose ( ) Closes a file which has been opened for use
getc ( ) Reads a character from a file
putc ( ) Writes a character to a file
fprintf ( ) Writes a set of data values to a file
fscanf ( ) Reads a set of data values from a file
getw ( ) Reads a integer from a file
putw ( ) Writes an integer to the file
fseek ( ) Sets the position to a desired point in the file
ftell ( ) Gives the current position in the file
rewind() Sets the position to the begining of the file
Defining and opening a file:
 If we want to store data in a file into the secondary memory, we must specify certain things about the file
to the operating system.
 They include the fielname, data structure, purpose.

17
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

 The general format of the function used for opening a file is


FILE *fp;
fp=fopen(“filename”,”mode”);
 The first statement declares the variable fp as a pointer to the data type FILE.
 As stated earlier, File is a structure that is defined in the I/O Library.
 The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp.
 This pointer, which contains all the information about the file, is subsequently used as a communication
link between the system and the program.
 The second statement also specifies the purpose of opening the file.
 The mode does this job.
R - open the file for read only.
W - open the file for writing only.
A - open the file for appending data to it.
Consider the following statements:
FILE *p1, *p2;
p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);
 In these statements, the p1 and p2 are created and assigned to open the files data and results respectively,
the file data is opened for reading and result is opened for writing.
 In case the results file already exists, its contents are deleted and the files are opened as a new file.
 If data file does not exist, error will occur.
Closing a file:
 The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);
 A file must be closed as soon as all operations on it have been completed.
 This would close the file associated with the file pointer.
….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….

fclose(p1);
fclose(p2)
Example:
#include< stdio.h >
main( )
{
file *f1;
printf(“Data input output”);
f1=fopen(“Input”,”w”); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/
putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“\n Data output \n”);
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)

18
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

printf(“%c”,c);
fclose(f1);
}
The getw and putw functions:
/*Example program for using getw and putw functions*/
#include< stdio.h >
main( )
{
FILE *f1,*f2,*f3;
int number I;
printf(“Contents of the data filen \n”);
f1=fopen(“DATA”,”W”);
for(I=1;I< 30;I++)
{
scanf(“%d”,&number);
if(number = = -1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF)/* Read from data file*/
{
if(number%2==0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“\n\nContents of the odd filen \n”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“\n\nContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}
The fprintf and fscanf functions:
 The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files.
 The first argument of these functions is a file pointer which specifies the file to be used.

19
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

General format of fprintf :


fprintf(fp,”control string”, list);
 Where fp is a file pointer associated with a file that has been opened for writing.
 The control string is file output specifications list may include variable, constant and string.
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
General format of fscanf :
fscanf(fp,”controlstring”,list);
 This statement would cause the reading of items in the control string.
Example:
fscanf(f2,”5s%d”,&item,&quantity”);
 Like scanf, fscanf also returns the number of items that are successfully read.
/*Program to handle mixed data types*/
#include< stdio.h >
main( )
{
FILE *fp;
int number,quantity,I;
float price,value;
char itemname[10],filename[10];
printf(“Input filename”);
scanf(“%s”,&filename);
fp=fopen(filename,”w”);
printf(“Input inventory data \n”);
printf(“Item name number price quantity \n”);
for(I=1;I< =3;I++)
{
fscanf(stdin,”%s%d%f%d”,&itemname,&number,&price,&quantity);
fprintf(fp,”%s%d%f%d”,itemname ,number,price,quantity);
}
fclose (fp);
fprintf(stdout,”nn”);
fp=fopen(filename,”r”);
printf(“Itemname, number, price, quantity ,value”);
for(I=1;I< =3;I++)
{
fscanf(fp,”%s%d%f%d”,&itemname,&number,&price,&quantity);
value=price*quantity;
fprintf(“stdout,”%s%d%f%d%d\n”,itemname,number,price,quantity,value);
}
fclose(fp);
}
RANDOM ACCESS TO FILES:
 Access individual records without searching through other records.
 Instant access to records in a file.

20
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

 Data can be inserted without destroying other data.


 Data previously stored can be updated or deleted without overwriting.
 Implemented using fixed length records.
 Sequential files do not have fixed length records.
0 100 200 300 400 500

} } byte offsets

}
}
}
}
}
100 100 100 100 100 100
bytes bytes bytes bytes bytes bytes
CREATING A RANDOM ACCESS FILE:
 Data unformatted (stored as "raw bytes") in random access files.
 All data of the same type (ints, for example) use the same memory.
 All records of the same type have a fixed length.
 Data not human readable.
UNFORMATTED I/O FUNCTIONS:
• fwrite - Transfer bytes from a location in memory to a file
• fread - Transfer bytes from a file to a location in memory
• fwrite( &number, sizeof( int ), 1, myPtr );
– &number - Location to transfer bytes from
– sizeof( int ) - Number of bytes to transfer
– 1 - For arrays, number of elements to transfer
In this case, "one element" of an array is being transferred
– myPtr - File to transfer to or from
– fread similar.
• Writing structs
• fwrite( &myObject, sizeof (struct myStruct), 1, myPtr );
– sizeof - Returns size in bytes of object in parentheses
• To write several array elements
– Pointer to array as first argument
– Number of elements to write as third argument
1. #include<stdio.h>
2. struct clientData
3. {
4. int acctNum;
5. char lastName[15];
6. char firstName[10];
7. double balance;
8. };
9. int main ( )
10. {
11. int i;
12. struct clientData blankClient = {0, "", "", 0.0};
13. FILE *cfPtr;
14. if((cfPtr = fopen("credit.dat","w"))==NULL)

21
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

15. printf("File could not be opened.\n");


16. else
17. {
18. for(i=1;i<=100;i++)
19. write(&blankClient,sizeof(structclientData),1,cfPtr);
20. fclose(cfPtr);
21. }
22. return 0;
23. }
WRITING DATA RANDOMLY TO A RANDOM ACCESS FILE:
• fseek
– Sets file position pointer to a specific position
– fseek( myPtr, offset, symbolic_constant);
• myPtr - pointer to file
• offset - file position pointer (0 is first location)
• symbolic_constant - specifies where in file we are reading from
• SEEK_SET - seek starts at beginning of file
• SEEK_CUR - seek starts at current location in file
• SEEK_END - seek starts at end of file
/* Writing randomly to a random access file*/
1. #include<stdio.h>
2. struct clientData
3. {
4. int acctNum;
5. char lastName[15];
6. char firstName[10];
7. double balance;
8. };
9. int main( )
10. {
11. int i;
12. struct clientData client = {0, "", "", 0.0};
13. FILE *cfPtr;
14. clrscr( );
15. if((cfPtr = fopen("credit.dat","r+"))==NULL)
16. printf("File could not be opened");
17. else
18. {
19. printf("Enter account number (1 to 100, 0 to end input)\n");
20. scanf("%d",&client.acctNum);
21. while(client.acctNum != 0)
22. {
23. printf("Enter lastname,firstname,balance\n?");
24. fscanf(stdin,"%s%s%lf",client.lastName,client.firstName,&client.balance);
25. fseek(cfPtr,(client.acctNum - 1) * sizeof(struct clientData),SEEK_SET);
26. fwrite(&client,sizeof(struct clientData),1,cfPtr);
27. printf("Enter account Number\n?");

22
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

28. scanf("%d",&client.acctNum);
29. }
30. fclose(cfPtr);
31. }
32. return 0;
33. }
READING DATA SEQUENTIALLY FROM A RANDOM ACCESS FILE:
• fread
– Reads a specified number of bytes from a file into memory.
– fread( &client, sizeof (struct clientData), 1, myPtr );
– Can read several fixed-size array elements
• Provide pointer to array
• Indicate number of elements to read
– To read multiple elements, specify in third argument.
/*Reading Data Sequentially from a Random Access File */
1.#include<stdio.h>
2.struct clientData
3. {
4. int acctNum;
5. char lastName[15];
6. char firstName[10];
7. double balance;
8. };
9.int main( )
10. {
11. int i;
12. struct clientData client = {0, "", "", 0.0};
13. FILE *cfPtr;
14. clrscr();
15. if((cfPtr = fopen("credit.dat","r"))==NULL)
16. printf("File could not be opened");
17. else
18. {
19. printf("%-6s%-16s%-11s%10s\n","Acct","Last Name","First Name", "Balance");
20. while(!feof(cfPtr))
21. {
22. fread(&client,sizeof(struct clientData),1,cfPtr);
23. if(client.acctNum != 0)
24. printf("%6d%16s%11s%10.2f\n",client.acctNum,client.lastName,client.firstName,client.balance);
25. }
26. fclose(cfPtr);
27. }
28. return 0;
29. }
BINARY FILES:
 Binary file is a sequence of bytes encoded in binary form for computer storage and processing purposes.
 Binary file formats includes text, images, sounds, compressed version of other files, etc.

23
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

Need For Binary Files:


 In text files , integer value occupies two bytes, but when it is stored in disk using fprintf( ), it occupies one
byte for each character i.e. 22157 occupies 5 bytes.
 Storing numerical data on the disk using either text mode become inefficient as it occupies more memory
space.
 Therefore binary files are used for reading and writing data in the files.
Binary Modes
Modes Description
rb Opens a binary file in read mode
wb Opens a binary file in write mode
ab Opens a binary file in append mode
r+b Opens an existing file in read and write mode
w+b Creates a new file in read and write mode
a+b Opens an existing file and writes data from the end of the file. If the file doesn’t exist,
data is written to the new file.
The fread and fwrite function takes four parameters:
 A memory address
 Number of bytes to read per block
 Number of blocks to read
 A file variable
For example:
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
 This fread statement says to read x bytes (size of rec) from the file ptr_myfile into memory address
&my_record.
 Only one block is requested.
 Changing the one into ten will read in ten blocks of x bytes at once.
Example:
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;

ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)

24
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

{
my_record.x= counter;
fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile);
}
fclose(ptr_myfile);
return 0;
}
 In this example we declare a structure rec with the members x,y and z of the type integer.
 In the main function we open (fopen) a file for writing (w).
 Then we check if the file is open, if not, an error message is displayed and we exit the program.
 In the “for loop” we fill the structure member x with a number.
 Then we write the record to the file.
 We do this ten times, thus creating ten records.
 After writing the ten records, we will close the file (don’t forget this).
 So now we have written to a file, let’s read from the file we have just created.
Example:
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
 The only two lines that are changed are the two lines in the “for loop”.
 With the fread we read-in the records (one by one).
 After we have read the record we print the member x (of that record).
 The only thing we need to explain is the fseek option.
 The function fseek must be declared like this:

25
CS3353- C PROGRAMMING AND DATA STRUCTURES UNIT-II C PROGRAMMING –ADVANCED FEATURES

int fseek(FILE * stream, long int offset, int whence);


 The fseek function sets the file position indicator for the stream pointed to by the stream.
 The new position, measured in characters from the beginning of the file, is obtained by adding offset to the
position specified by whence.
 Three macros are declared in stdio.h called: SEEK_SET, SEEK_CUR and SEEK_END.
 If the position declared by whence is SEEK_SET, then the position is the beginning of the file.
 The SEEK_END can be used if you want to go to the end of the file. (Using negative numbers it is
possible to move from the end of the file.)
 If whence is SEEK_CUR then the position is set, x bytes, from the current position.
Example:
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;

ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=9; counter >= 0; counter--)
{
fseek(ptr_myfile,sizeof(struct rec)*counter,SEEK_SET);
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
 In this example we are using fseek to seek the last record in the file.
 This record we read with fread statement and with the printf statement we print member x of the structure
my_record.
 As you can see the “for loop” also changed. The “for loop” will now countdown to zero.
 This counter is then used in the fseek statement to set the file pointer at the desired record.
 The result is that we read-in the records in the reverse order.

26

You might also like