You are on page 1of 36

Data structure using c

Chapter-1 Pointers [18-Marks]

Introduction :-
The pointer is a derived data type in ‘c’, build from one of the fundamental data type available in ‘c’.
 Pointer contains memory address hence it can be used to access and manipulate data stored in memory.
Concept of Pointer:-
The computer memory is a sequential collection of storage cells has shown bellow:-
Memory cell-
0

65535

Each cell is having a separate address associate with it. Where ever a variable is declared the system allocates
some where in memory.
Ex:- int quantity =100;
The above statement instruct the system to find allocation for the integer variable quantity and stores
100 in them.

Variable -> quantity


Value -> 100
Address -> 5000

Fig. Variable

Since memory address is a number, it can be assigned to some variable.

Chethan H S , Lecturer Page 1


Data structure using c

That can be stored in the memory. The variables that holds the address of the another variable is called
as pointer variable.
Variable Value Address Quantity
100 5000
P 5000 5048

Fig. Pointer variable

We can access the value of variable quantity using the value of ‘p’ (since) hence we can say that ‘p’ is
pointing to quantity.
 Pointer can built on three concepts:-
I. Pointer constants
II. Pointer value
III. Pointer variable

1. Pointer constant: Memory address within a computer is refers to as pointer constants, which can’t be
changed.

2. Pointer value :- Address of variable can be stored using ‘&’ symbol to pointer and value of variable
can be accessed using *.
Ex:- *p.

3. Pointer variable :- A pointer value is stored into interior variable called pointer variable.
Declaring & Initializing the pointers
Declaring pointer variables:
Syntax:
Datatype *ptr_name;
This indicates 3 things to the compiler

1) The (*) asterisk tells that the variable ptr_name is the pointer variable.
2) The pointer variable ptr_name (means) memory location.
3) The ptr_name points to the variable of type datatype.
Ex: int *p.
Declare the pointer variable ‘p’ which is point to integer datatype.
Ex: float *x.
Declare the pointer ‘x’ which is pointing to floating data type.

Chethan H S , Lecturer Page 2


Data structure using c

Pointer variables are declared as normal variable as shown below.

Int *p;
Int * p;
Int * p;
Ex: int x, y, *p;
x=10;
p=&x;
y=*p;
Initialization Of Pointer
The process of assigning the address of the variable to the pointer variable is known as Initialization.
All uninitialized pointer will have some unknown values which is not valid.
Ex: int quantity = 100;
Int *p; |*declaration*|
Method 1: p = &quantity; |*initialization*|
(or)
Method 2: int *p = &quantity;
The following are alos valid initialization of the pointers.
int *P = Null;
int *p = o; => Valid Values.
When we declare a pointer to be of integer type the pointer must hold address of integer variable only.
‘K’ should be taken to avoid wrong pointer a assignment.
Ex: float a, b;
Int *p;
P = &a; |*wrong Assignment*|
Pointers are flexible in such a way that it can point to different variable at different time.
Ex: int x, y, z;
int * p;
p = &x;
p = &y;

Chethan H S , Lecturer Page 3


Data structure using c

p = &z;

we can also use different pointers points to same variables.

P1 P2 P3

ex:
int *p1,*p2,*p3;
p1=&x;
p2=&x;
p3=&x;
Accessing pointers variables using pointers:
once a pointer has been initialized with an address of variable then we can access the value of
variable using unary operator(*) unary operator called indirection (or) derefferring operator.
ex: int quantity=100 ; y;
int *p ;
p = & quantity ;
y =* p ;
*p = 200;
the fourth line contains operator (*) when it appear before the pointer variable on right hand side of
equal sign the pointer returns the value of the variable whose address it is holding.
WAP to illustrate the use of indirection operand (*) to access the value pointed to by a pointer:
# include<stdio.h>
#include<conio.h>
void main()
{

Chethan H S , Lecturer Page 4


Data structure using c

int x, y ;
int *p ;
x =10 ;
p = &x ;
printf (“ the value of x is %d\n”, x);
printf (“ %d is stored at address % u\n”, x , & x);
printf (“ %d is stored at address %u\n”, *p , p);
printf (“%d is stored at address %u\n”,p , & p);
printf (“%d is stored at address %u\n”, y, & y);
*p = 25;
printf (“ now x = %d\n”, x);
}
Variable value address
X 25 4000
P 4000 4100
Y 10 4200

output :
the value of x = 10
10 is stored at address 4000
10 is stored at address 4000
4000 is stored at address 4100
10 is stored at address 4200
now x =25

Pointer Arithmatic :
C – allows us to add integers to [or] subtract integers from pointers , subtract one pointer from
other.
ex : y = *p1 - *p2 ;
sum = sum + *p1;
*p2 = 10/* p1 ;

Chethan H S , Lecturer Page 5


Data structure using c

*p2 = *p1 + 10 ;
are all valid statements if p1 & p2 are properly declared and intilizes pointers.
we can do use of short & operators with the pointers p1 ++;
ex : ++ * p1;
p1 - - ;
sum + = *p ;
we can also use pointers in division & multiplication as operation.
→the following are not valid statements :
ex : p1/p2 ;
p1 * p2 ;
p1 + p2 ;
p1 – p2 ;
WAP to illustrate the use of pointers in arithmetic operation :
#include<stdio.h>
#include<conio.h>
void main()
{
int a , b , *p1 , *p2 , x; y; z;
a = 12 ,b =4 ;
p1 = &a , p2 = &b ;
x = *p1 ** p2 -6 ;
y = 16- *p1/ *p2 + 10;
printf (“ address of a = % u\n ” , p1) ;
printf (“ address of b = %u\n ‘, p2) ;
printf (“ a = %d , b = %d\n “ , a, b) ;
printf (“ x = %d , y =%d\n “ , x , y) ;
*p2 = *p2 + 3 ;
* p1 = *p2 – 5 ;
Z = *p1 ** p2 – 6 ;
printf (“a =%d , b = %d , Z = %d , a , b , Z) ;
}

Chethan H S , Lecturer Page 6


Data structure using c

1) when an array is declared the compiler allocates base address and sufficient amount of
memory to store all elements of array in continuous memory location.
2) Base address is the location of first elements & the array name is defines as constant
pointer to the 1st element.
ex : int a[5] = {1,2,3,4,5}

Element→ a[0] a[1] a[2] a[3] a[4]


value→ 1 2 3 4 5

Address→ 1000 1002 1004 1006 1008

Base address
‘ a ‘ is the constant pointer , pointing to the 1st element that is x = 1000 or x =& a[0] =100
If ‘ p’ is declared as integer pointer then we can used p to point to the array ‘a’ .
int *p ;
p=a;
or
p = &a[0] ;
Now the relationship b/w p and a shown as follows :
p = & a[0] =1000
p+1 = &a[1] =1002
p+2 = &a[2] =1004
p+3 = &a[3] =1006
p+4 = &a[4] = 1008
The address of the element is calculated using base address , and scale factor of data type .
ex : Net address = Base address +(3 * Scale factor of int)
= 1000 + (3*2)
= 1000 + 6 = 1006

Address of a[4]=1000+(4*2)

Chethan H S , Lecturer Page 7


Data structure using c

=1000+8
=1008
To handle arrays instead of using array index in we can use pointers to access array element sense, pointer
accessing method is much faster than array indexing.

WAP using Pointers to compute sum of all the elements stored in the array:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int *p,sum,I;
Int x[5]={5,9,6,3,7}
I=0;
P=x;
Printf(“element\t values\t address\n”);
While(<5)
{
Printf(“x[%d}\t %d\t %u\n”,I,*p,p);
Sum=sum-*p;
I++;
P++;
}
Printf(“\n sum=%d\n”,sum);
Printf(“&x[0]=%u\n”,&x[0]):
Printf(“p=%u\n”,p
}

OUTPUT
Element Value address
X[0] 5 1000
X[1] 9 1002

Chethan H S , Lecturer Page 8


Data structure using c

X[2] 6 1004
X[3] 3 1006
X[4] 7 1008
Sum=30
&x[0]=1000
P=1010

Pointers & character strings


Strings can be created as character array as follows
Char str[6]=”Delhi”;
(OR)
Char*str=”Delhi”;
The complier automatically insert a null character at the end of string(10).
Another way of creating string is
Ex: char*str=”Delhi”;
This creats a string and stoes it’s address in the pointer str. The pointer str pointer to the 1 st character of the
string “Delhi”

D e l h i \0

Ex: char *s;


S=”good”;
Here ‘S’ is a pointer to the string, it is also the name of the string.
We can print the content of the string ‘s’ using printf or puts Function.
Ex: printf(%s”,5);
(OR)
Puts(s)
WAP using pointers to determine length of a character string:
#include<stdio.h>
#include<conio.h>
Void main()
Chethan H S , Lecturer Page 9
Data structure using c

{
Char *x=’DELHI”;
Int length;
Char*p;
P=x;
Printf(“%s\n”,x);
While(*p!=’\0’)
{
Printf(“%c Is stored at address %u\n”,*p);
P++;
}
Length=p-x;
Printf(“\n length of string = %d\n”,length);
}
DELHI
D is stored at 1000
E is stored at 1001
L is stored at 1002
H is stored at 1003
I is stored at 1004
Length of string is = 5
Pointer and functions:
We can pass the address of variable as an argument to function. So, the parameter receiving the address should
be pointer. The process of calling function using pointer to pass the address of variable is known as call by
reference the function which is called by reference can change the value of variable used in the called
Ex:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int x=10;

Chethan H S , Lecturer Page 10


Data structure using c

Change(&x);
Printf(“%d”,x);
}

change (int*p)
{
*p=*p+10;
}
When the function change is called the address of the variable x is passed to the function change the
statement *p=*p+10 adds 10 to the value stored in adderss ‘p’ . so he value of ‘x’ becomes 20.
Write a function using pointer to exchange the value stored in two location in memory:
void exchange(int *a,int *b);
void main()
{
int x,y;
x=100;
y=200;
printf(“before exchanging x=%d y=%d\n”,x,y);
exchange(&x,&y);
printf(“after exchanging x=%d y=%d\n”,x,y);
}
void exchange(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}

Chethan H S , Lecturer Page 11


Data structure using c

OUTPUT:
Before exchanging x=100 y=200
After exchanging x=200 y=100
Pointers to function
1) Every function defined in ‘c’ have some base address associated with it.
2) This base address is used in the function definition . this base address is stored in a pointer called as
an function pointer.
3) The syntax for declaring pointer to function is :-

return type(*fp_name) (datatype argument1,datatype argument2);

Ex:- int (*fp) (int a,int b);

Program for addition of two numbers using pinters to function:


#include<stdio.h>
#include<conio.h>
int add(int a,int b)
{
return(a+b);
}
void main()
{
int (*fp) (int,int);
fp=add;
printf(“The addition of 2 number is %d”,fp(50,30));
}

Pointer and structures:


1) Structure is collection of variables of different datatype.
2) The variables declared with in a structure in a structure are called members of the structure .
Syntax for declaring the structure:
Struct name of_structure
{
datatype member1;
datatype member2;
datatype member3;
}tagname;
Example:-
struct student
{
char name[10];

Chethan H S , Lecturer Page 12


Data structure using c

int rollno;
char address[30];
}s;

WAP to accept the marks of 3 subjects along with rollno of 10 students and print the same using
pointer to structure:(Nov-2009)

#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[10];
int m1;
int m2;
int m3;
}s[10];
void main()
{
int i;
struct student *p;
clrscr();
for(i=1;i<=10;i++)
{
printf(“enter student details\n“);
scanf(“%d%s%d%d%d”,&s[i].rollno,s[i].name,&s[i].m1,&s[i].m2,&s[i].m3);
for(i=1;i<=10;i++)
{
printf(“%d%s%d%d%d”,p rollno,p name,p m1,p m2,p m3);
p++;
}
getch();
}
}

Array of pointers:
Array of pointers means the array locations containing the address of another variables which is having
same values.

Example:
int *a[3];
int x,y,z;

Chethan H S , Lecturer Page 13


Data structure using c

x=10;
y=20;
z=30;
a[0]=&x;
a[1]=&y;
a[2]=&z;

a[0] a[1] a[2]

1010 1002 1020

X Y Z

30
10 20

1010 1002 1020

Array of pointer

2. The array of pointer is the concept which is used when we want to store multiple strings in an array
Ex: char name [3] [25];

The above arrays of string include 3 names each with 25 characters. So total storage required is 75 bytes.

Individual string may not be equal. Hence instead of making each row of fixed no. of character we can
make it to point to a string of variable length.

Ex: string of variable name as bellow ;


Char *name [3]={“Bangalore”, “Pune “, “Delhi”};

Write a C – program to illustrate a concept of array of a pointer:

Chethan H S , Lecturer Page 14


Data structure using c

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main( )
{
int *a[10];
int i, x, y, z;
clrscr();
printf(“Enter the 3 numbers “);
scanf(“%d%d%d ”, &x,&y,&x);
a[0]=&x;
a[1]=&y;
a[2]=&z;
for (i=1;i<3;i++)
{
printf(“in the element %d is stored at location %d\n”,*a[i],a[i]);
}
getch();
}

Chethan H S , Lecturer Page 15


Data structure using c

 List of the difference between call by value and call by reference

Call by value Call by reference


1. In call by value mechanism 1) In this method address of the
the values of the variables are variable are passed through as
passed as an argument an argument.
2. Any changes made in sub- 2) Any changes made in sub-
function will not effect the function will effect in main
main function. function.
3. The actual values of the 3) The actual values of variable
variable remain unaffected. effected.
4. Execute is slow 4) Execute is fast.
5. Occupies more space 5) Occupies less space.

 Important question:
1) What is pointer ? How a pointer is initialized.(5)
2) Explain how to access the variable using pointers with example .(5)
3) What are pointer arithmetic operation and Explain .(4)
4) Define pointer and Explain pointer arithmetic.(6)
5) Write a program to find smallest of n numbers using pointer.(4)
6) Difference between call by value and call by reference parameter passing technique with
example.(4)
7) Write a note on call by reference .(4).
8) Write a c program that uses a function to swap the element using pointer concept .(6)
9) Explain pointer and function concept with an example.(5)
10) Explain pointer to function with example .(4)
11) Distinguish between address and indirect operator .
Chethan H S , Lecturer Page 16
Data structure using c

12) Write a note on structure on pointers.(5)


13) Write a c program to accept the marks of three subject along with roll no of 10 student and
print same using pointer to structure .(8)
14) Explain pointers on array .(5)
15) Explain pointers and character strings .(5)
16) Explain how to declare and initialize pointer with example .

Chethan H S , Lecturer Page 17


Data structure using c

Dynamic memory allocation

Introduction

1) In programming the no of data items may vary during the execution of the program.
2) The no. of element may increase or decrease hence we need to allocate more memory to accommodate
or shorten to de allocate
3) In c , we can allocate and de allocate the memory dynamically .dynamic memory allocate optimizes
the performance of storage .

Dynamic memory allocation

1) The process of allocating memory at run time is known as dynamic memory allocation .
2) C language is does not have facility to specify an array size at run time .
3) C program uses the memory which is divided into three parts
1. Static area
2. Stack area
3. Heap area

4) Static area stores the global data ,stack area is for local area data and heap area is for
allocate or de allocate memory under program control .
5) Thus stack and heap area are the parts of dynamic memory management
6) The stack and heap area grows towards each other hence there areas are fixable .

OS programs
Programmer code

Static commonly

Chethan H S , Lecturer Page 18


Data structure using c

For static variable

Stuck memory Stock can grow in


For local data Downward direction

Heap area

Heap can grow in


Upward direction

Memory Model

C-supports some following function for the purpose of memory management.

Function Purpose
Allocates a memory desire size and returns the point to the 1st byte
i. Malloc ( )
of allocate space.
Allocates space for an array of elements, initialize them to zero and
ii. Calloc ( )
returns a pointer to the memory.

iii. Free ( ) Deallocates the previously allocated space.

iv. Realloc ( ) Modifies the size of previous allocated space.

Allocating a block of memory:-

i.Malloc:- The malloc function is used to allocate the memory of desire size. By default malloc returns the
void pointer.
ii. If memory is allocated, then it needs to typecast the returning value of malloc function.
Syntax:- void * malloc (size)

Chethan H S , Lecturer Page 19


Data structure using c

EX: - int * i;
i = (int *)malloc (size of (int));
The above statement allocates integer type of data.
It is typecast by writing (int *) before malloc.
Size of operation is used to obtain size of integer variable.

Allocating multiple blocks of memory:-


Calloc:-
i. Malloc returns a block of memory that is allocated for the programmer to use but this block of
memory is uninitialized. Hence we need to initialize the memory.
ii. There is an another way to allocate a memory by using calloc function.
iii. The calloc function allocates a memory and them initialized into zero.

Syntax:- void * calloc (number of elements ,size of elements);

Ex:
Int *p;
p= (int *) calloc (10,size of (int));

The above statement allocates memory of 10 single integers and the memory address of 10 elements will be
assigned to pointer.

Realizing the used space:-

i. The allocated block of memory can be deleted using free function.

Syntax:- void free (void * pointer);

Ex:- int * i;
i= (int *) malloc (size of (int));
free (i);

Chethan H S , Lecturer Page 20


Data structure using c

Altering the size of memory:-


Realloc:-
The realloc is a function that makes a chunk of memory. This memory is allocated with malloc
of calloc function then the size of the specified memory is altered.

Syntax: - realloc( void *ptr, size);

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
Void main ()
{
Int i,*p,*m,n;
Int val;
Clrscr ()
Printf (“enter the total no of data items \n”);
Scanf (“%d”,&n);
P=(int * ) calloc (n, size of (n));
For (i=0; i<n; i++)
{
Printf (“%d th memory block contains %d”,I,*p);
*p++;
}
Printf (“\n enter the new size\n”);
Scanf (“%d”,&n);
p= (int *) realloc (p , n+10);
m=p;
for (i=0; i<n; i++)
{

Chethan H S , Lecturer Page 21


Data structure using c

Printf (“ Enter the data”);


Scanf(“%d”, &val);
*m=val;
}
For (i=0; i<n; i++)
{
Printf(“\n %d th memory block contains %d “,I,*m,*p++;
}
free(p);
getch();
}

Chethan H S , Lecturer Page 22


Data structure using c

Difference between Malloc & Calloc

Malloc Calloc

1. Malloc allocates single block of memory. 1.Calloc allocates a multiple block of memory.
2. Memory block is uninitialized. 2.Block of memory will be initialized to zero.
3.Malloc takes one parameter i.e size of block. 3.Calloc takes two parameter size & no of block.
4.void * malloc (size). 4.void * calloc (n,size of (m))
5. int *i; 5. int *i;
i=(int*)malloc(size of (int)). i=(int*)calloc(10,size of (int))

Chethan H S , Lecturer Page 23


Data structure using c

Chapter 3 FILES 14marks

Introduction
Printf and scanf is used to read and write data which are console oriented input output function but to read
and write large volumes of data console oriented to Function Faces two problem
1.It is time consuming to handle large volumes of data through terminals.
2.The entire data is lost when either the program name is terminated or computer is turned off hence to over
come the above problem we use concept of files to store data.
A file is a place on the disk where a group of related data is stored. C-supports the no. of Functions
that have the ability to perform basic file operation such as-------
1. Nameing a File
2. Opening a file.
3. Writing data to a File.
4. Reading data from File
5. Closing a File.

1.Definig &opening a File


To store the data in a file in a secondary storage, we must specify the following things about the File to
operating system.

2.File name
It is a string of character that up a valid Filename
EX:- Book.doc ,Input.c , etc

3.Data Structure
Ds of a file is defined as file in the library of standard IO function decleared as type FILE (FILE is adefined
data type)

4.Purpose : When we open a File that is for reading or writing data to file.
Syntax: File *fp;
Fp=Fopen(“filename”,”made”);

Chethan H S , Lecturer Page 24


Data structure using c

Where Fp is the pointer where is of type file and it is a File pointer.

The second statement opens the File named File name and assign the identifier to Fp.

The Second statement also specifies the pupose of opening the file by using mode specification.Mode can be
one of the Foloowing------
r-> Open the File for reading
w-> Open the file for writing.
a-> Open the file for appending data to it.
 Both the Filename and mode mustbe specified in double quates.
When the file is open the following things may happens .

i. When a mode is writing a file with a specified name is created if the file does not exists .If it exists
the contains are deleted .
ii. When the mode is appending the File is open with the current content. A file is created with the
specified name if it does not exist.
iii. When the mode is reading,if the file is existed then the File is opened with the current content
otherwise an error occurs.

Example: FILE *p1,*p2;


P1=Fopen(“data”,’”r”)
P2=Fopen(“result”,”w”)

Closing a File

A File must be closed once all the operation on it gave been completed and all the links to the file are broken
once we cloxse the File.Clossing a file also prevents from accidental misuse of File and also enable to open
number of File symeiteniously.When we want to reopen the same File in the different mode it is require to
close the file.
Syntax: Fclose(file_pointer)

Chethan H S , Lecturer Page 25


Data structure using c

Input-Output operation on the Files:


After a file is open the read-write to the File can be accomplish using the standard 10 tooins listed bellow----
--

Function name Operation


1) Fopen() 1)Creates a new file or open an
existing File
2) Fclose() 2)Close a file which has been opened
for use.
3) Fscanf() 3)Reads a set of data values to a file

4) Fprintf() 4)Writes a set of data values to the q


File
5) getc() 5)Reads a charcter froma file .

 fputc( ) -write a character to a file


 getw( )-reads an integer to a file
 putw( )-write an integer to a file
 fgets( )-reads a string to a file
 fputs( )-write a string to a file
 rewind( )-sets the position to beginning of the file
 fseek( )-sets the position to the desire point in a file
 ftell( )-indicates the current position of the cursor in the file.

Write a program to read a character and print the same.


#include<stdio.h>
#include<conio.h>
Void main()
{

Chethan H S , Lecturer Page 26


Data structure using c

Char c;
File *fptr;
Clrscr();
fptr=fopen(“book.doc”,”w”);
printf(“enter the character\n”);
scanf(“%c”,&c);
fputc(c,fptr);
fclose(fptr);
fptr=fopen(“book.doc”,”r”);
c=fgetc(fptr);
printf(“%c”,c);
fclose(fptr);
getch();
}
The following statement:
fputc(c, fp);
Writes the character contains the variable ‘c’ to the file associated with FILE pointer fp.
fgetc() is used to read a character from the file whose file pointer fp.
fgetc(fp);
fp moves by one character position for every operation fgetc() or fputc()
write a program to read the character data from the keyboard write it to the file called “INPUT”
again read the data from the same file and display on the screen.
#include<stdio.h>
#include<conio.h>
Void main()
{
Char c;
FILE *fptr;
Clrscr();
fptr= fopen(“INPUT”, ”w”);
Printf(“entre the character\n”);

Chethan H S , Lecturer Page 27


Data structure using c

Scanf(“%c”,&c);
fputc(c,fptr);
fclose(fptr);
fptr=fopen(“INPUT”,”r”);
c=fgetc(ptr);
printf(“%c”,c);
fclose(fptr);
getch();
}
getw() and putw()
These are integer oriented function similar to fgetc() and fputc() but use to read and write the integer.
Syntax :
putw(1,fp);
Which writes the integer content 1.
To the file associated with file pointer fp , getw(fp) which is used to read a integer from a file whose file
pointer is fp.
Write a program to read the integer value from the keyboard. write it to a file called “count” again
read the data from the same file and display on the screen.
#include<stdio.h>
#include<conio.h>
Void main()
{
int a;
FILE * fptr;
clrscr();
fptr=fopen(“count”, ”w”);
pritnf(“enter the integer\n”);
scanf(“%d”,&a);
putw(a,fptr);
fclose(fptr);
fptr=fopen(“count”,”r”);

Chethan H S , Lecturer Page 28


Data structure using c

a=getw(fptr);
printf(“%d”,a);
fclose(fptr);
getch();
}
Write a c program to read 10 integers into the file called data (the odd integer should be written to the
file odd and even integer should be written to the file even) file and print the same on the screen.
#include<stdio.h>
#include<conio.h>
Void main()
{
FILE *fp1, fp2, fp3;
int no, i;
fp= fopen(“data”, ”w”);
printf(“enter the integer values\n”);
for (i=1;i<=10;i++)
{
Scanf(“%d”, &no);
Putw(no, fp1);
}
fclose(fp1);
fp1=fopen(“data”,”r”);
fp2=fopen(“even”,”w”);
fp3=fopen(“odd”,”w”);
while(no=getw(fp1)!=EOF)
{
If(no%2==0)
Putw(fp2);
else
Putw(fp3);
}

Chethan H S , Lecturer Page 29


Data structure using c

fclose(fp1);
fclose(fp2);
fclose(fp3);
fp2=fopen(“even”,”r”);
fp3=fopen(“odd”,”r”);
printf(“contents of sum file\n”);
while(no=getw(fp2)!=EOF)
printf(“4%”,no);
printf(“contents of add\n”);
while (no= getw fp3)!=EOF)
printf(“%d”, no);
fclose(fp2);
fclose(fp3);
getch();
}
fprintf() & fscanf():-
fprintf & fscanf can handle a group of mixed date simultaneously .the function fprintf & fscanf work same
as printf & scanf function but they perform IO operation on files .the general form of & fprintf
Syntax:-
fprintf (fp ,”control string ”,list);
Where fp is a file pointer associated with a file that has been opened for writting
The control string contains o/p specifications for the items in the list
Example:- fprintf ( fp,”%d %s ”, roll no ,name);
The general form of fscanf is
Syntax: -fscanf(fp,” control string”,& list);
Example:- fscanf (fp,”%d %s ”,&roll no, name);
Write open a file name invertory ,reads & prints the follows
Date:-
File name number Price quantity
AAA-1 111 17.50 115
BBB-2 125 36.00 75

Chethan H S , Lecturer Page 30


Data structure using c

CCC-3 247 31.75 104


Extend the program me to read this date from the file invertry & display the invertry table with
the value of each item
#include <stdio.h>
#include <conio.h>
Void main()
{
FILE *fp;
int number ,price ,quantity;
Char filename[10];
clrscr();
fp= fopen(“Invertry”, ”w”);
fprintf(“fp”, Filename\ number\t price\t quantity\t);
Printf(“enter the details\n”);
for(i=0;i<3;i++)
{
Scanf(“%s %d % d %d”, filename, &number, &price ,&quantity);
Fprintf(fp,”%s\t %d\t %d\t %d\n”, filename, number, price, quantity);
}
Fclose(fp);
fp=fopen(“Invertry”, ”r”);
Printf(“filename\t number\t price\t quantity\t total value\n”);
for(i=0;i<3;i++)
{
fscanf(fp”%s %d %d %d” ,filename, &number, &price, & quantity);
total value=price*quantity;
Printf(“%s\t %d\t %d\t %d\t %d\n”, filename, number, price, quantity, total value);
fclose(fp);
getch();
}
fgets() & fputs():-

Chethan H S , Lecturer Page 31


Data structure using c

These are string oriented function which is used to read & write the string variable the following
statement :
fputs (s, fp);
Writes the string content in string variable ‘s’ to the file associated with file pointer fp
Fgets() is used to read string from the file
Syntax:-
Fgets(str, size, fp);
 Where str is the output variable where the string will be store after reading
 The size is nothing but length of the string to be read including the null character
 Fp is the file pointer
Write a c program to illustrate fgets() and fputs() functions :-
#include <stdio.h>
#include <conio.h>
Void main( )
{
FILE *fp;
Char s1[10],s2[10];
fp=fopen(“string”, ”w”);
Scanf(“%s”,s1);
fputs (s1,fp);
fclose (fp);
fp=fopen(“string”,” r”);
fgets (s2,10,fp);
Printf(“%s”,s2);
fclose(fp);
}
Error handling during i/o operation:-
It is possible that an error may occur during i/o operation on file ,t ypical error situation
can include
 Trying to read beyond the end of the file
 Device overflow

Chethan H S , Lecturer Page 32


Data structure using c

 Trying to read a file that has not been opened or created


 Trying to perform an operation on a file when the file is opened for another type of
operation
 Opening a file with an invalid file name. if we fail to check read write error the
program may behave abnormally and may lead to premature termination of the program
or it may give incorrect output

Deal with i/o errors in the file. FEOF( ) can be used to test for an end of the file condition.
Ex: if feof(fp==null
{
Printf(“file cannot be opened\n”);
}
Ex: if( feof (fp))
{
Printf(“end of the file\n”);
}
fp is a pointer to the file that has opened for reading. The above statement would display
end of file on reaching the end of file condition
ferror()
The function ferror reports the status of the file
if (ferror((fp)!=0))
{
Printf(“error\n”);
}
Here fp is a file pointer and ferror returns zero. If no error occurred else non-zero integer is
return. If any error has been detected during processing
Random access to the file

Chethan H S , Lecturer Page 33


Data structure using c

Sometimes we will be interested in reading a part of data from a file rather than reading
complete data. We must be able to access data from file randomly but not sequentially
The following functions 1)Ftell() 2) rewind() 3) Fseek are available in the i/o library.

I. Ftell(): It takes a file pointer as an argument & returns the number of type long
corresponding to the current position
Syntax: x=ftell(fp);

II. Rewind(): It takes file pointer as a parameter & reset the position to the beginning of
file.

Syntax: rewind(fp)
X=ftell(fp)
III. Fseek() : It is used to move the file position to a desired location within a file.

Syntax: fseek(file_ptr ,offset ,position );

File ptr is a pointer to the file concern.


Offset is a number or variable of type long.
Position is an integer number & it can takeone of the following three values-

Value Meaning

0 Beginning of file
1 Current position
2 End of the file

Offset specifies the number of positions to be move from the location specified by position value.
Example:
fseek(fp,m,0)-move the pointer from beginning m bytes forward.
fseek(fp,m,1)-move the pointer from current position m bytes forward.
fseek(fp,-m ,1)-move the pointer from current position m bytes backward.

Chethan H S , Lecturer Page 34


Data structure using c

fseek(fp,-m, 2)-move the file pointer from end of the file by m bytes backward.
Command lines argument:
The interface by which allows the user to interact with the computer by providing instruction in the form of
_ is called command line interface.
Example: copy t1.c t2.c
The above function copy accept the file t1.c and copies the content of t1.c to t2.c as parameter are pass to
the functions, the parameter can also be passed to the function main .when the programme is – are called
command line arguments.
Syntax: void main (int argc, char * argv [] )

-----

Where “argc” is an integer value here “argc” means argument count.


“argv” is an array of strings, here “argv” means argument array.
for the above statement the “argc” value will be 3. since it passing 3 argument through command prompt.
Each of the argument will be stored in the argument vector.
argv [0] contains copy
argv [1] contains t1.c
argv [2] contains t2.c.

Important question on Files chapter:-

1. Write a program to count no of digits ,lines and space in a file .


2. Explain with an example the different formatted input output operation that can be performed on
files .
3. What are random access files
4. Explain getc( ),fprintf()
5. Wap to create library file .information pertaining to book is – book no .title ,author ,publisher
,price extend your program to display the content of file .
6. What is a file ? hoe is file declared open and closes .
7. Write a note on fseek(),ftell().
8. What are the various modes for handling a file.
9. How is a file different from an array .
10. Write a note on basic file acess mode .

Chethan H S , Lecturer Page 35


Data structure using c

11. Write a c program to copy the contents of one file to another file .
12. Explain opening a file and closing the file.
13. Differentiate between following function
1.printf and fprintf
2.feof and ferror
3.getc and getw
14. write a c program to copy one file to another file use command line argument to specifies the
file name .
15.explain briefly the built in function for character and integer file operation in file handling

Chethan H S , Lecturer Page 36