0% found this document useful (0 votes)
1 views45 pages

Pointers, Structures, Files

pointers,structures,files
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views45 pages

Pointers, Structures, Files

pointers,structures,files
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Syllabus:

Pointers, Structures, Files


Pointers: Concept of a Pointer, Initialisation of pointer variables, pointers as
function arguments, passing by address, Dangling memory, address
arithmetic, character pointers and functions, pointers to pointers, Dynamic
memory management functions, command line arguments.
Structures: Derived types,Structuresdeclaration, Initialization of structures,
accessing structures, nested structures, arrays of structures, structures and
functions, pointers to structures, self referential structures, unions, typedef,
bit-fields.
Data Files: Declaring, Opening, and Closing File Streams, Reading from and
Writing to Text Files, Random File

Introduction to pointers
C provides the important feature of data manipulations with the address of
the variables, the execution time is very much reduced such concept is possible
with the special data type called Pointers.
Definition:
A pointer is a variable which stores the address of another variable.
Features of pointers:
 Pointers save the memory space.
 Execution time with pointer is faster because data is manipulated with the
address i.e; direct access to memory location.
 The memory is accessed efficiently with the pointers. The pointers assign the
memory space and can be released after use. Dynamically memory is
allocated.
 Pointers are used with data structures. They are useful for representing 2-d
and multidimensional arrays.
 It reduces the length & complexity of programs.
 It increases the execution speed and thus reduces the program execution
time.
 Pointers can be used to pass information back and forth between a function.
In particular, pointers provide a way to return multiple data items from a
function via function arguments.
 Pointers are also closely associated with arrays and therefore provide an
alternative way to access individual array elements.
 Pointers are used in file handling.
 The computer memory is a sequential collection of storage cells.

Declaration:
datatype *ptr_name;
This tells the compiler three things about the variable ptr_name.
1. The * tells that the variable ptr_name is a pointer variable and it stores address
of a variable of given datatype.
2. ptr_name needs a memory location.
3. ptr_name points to a variable of type datatype.

Ex:
int *p;
Declares the variable p as a pointer variable, that points to an integer data type.
Remember that the type int refers to the datatype of the variable being pointed to
by p and not the type of the pointer.
Similarly
float *x;

declares x as a pointer to a floating point variable.


Pointer initialization :
Once a pointer variable has been declared, it can be made to point to a variable
using an assignment statement and address operator such as
p = &a;
which causes p to point to a.
i.e. p now contains the address of ‘a’. This is known as pointer initialization. Before
the pointer is initialized, it should not be used.
Pointer:- A pointer is a variable which stores the address of another variable.
Declaration:-Pointer declaration is similar to normal variable declaration but
preceded by a *
Syntax:- data type *identifier;
Example:- int *p;
Initialization:- datatype *identifier=address;
Example:- int n;
int *p=&n;
NULL:-NULL pointer value(empty address)
int *p=NULL;
int *p=0;
Empty address can be assigned by initializing or assigning the pointer with NULL or
0 directly.
It is error to initialize the addresses (except 0) to the pointer directly. The following
is error.
int *p=4008;//error

int x=10;
int *p=&x;

Address of a variable which the


pointer points
Value of variable or
value at address of
10 X 504
variable
504 816
X ptr
Variable name
Pointer name

A pointer can point to only its intended datatype address location. For example,
integer pointer cannot point to floating point variable’s address location.
Accessing a variable through its pointer

 The address operator(&) returns address of a variable.


 The value stored at a given address is called value at the address.
 It can be accessed through the indirection operator(*).
 This is also called as dereference operator.

Eg:- int x=10,y;


int *p;
p=&x;
y=*p;//y=x

This statement instructs the system to find a location for the integer variable ‘a’ and
puts the value 50 in that location.

Let us assume that the system has chosen the address location 2000 for a.
printf(“a=%d address=%u\n”a, &a);
output:
a=50 address=2000

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,x;
clrscr();
x=10;
p=&x;
printf("\n Value of x is %d", x)
printf("\n address of x is %u", &x)
printf("\n address stored in p(value of p) is %u", p)
printf("\n Value present at address stored in p (value of x) is %d", *p)
printf(“ \n *(&x):%d is equal to x:%d”,*(&x),x);
printf(“ \n &x:%u is equal to p:%u”, &x, p);
getch();
}
OUTPUT:
Value of x is 10
address of x is 504
address stored in p(value of p) is 504
Value present at address stored in p (value of x) is 10
*(&x):10 is equal to x: 10
&x:504 is equal to p:504

Size of the Pointer:


Any type of pointer allocates two bytes of memory because it stores address of
memory [Link] c language the programme keep ([memory]) size is 64 kilo
[Link] is in unsigned integer range.
NOTE:- Any type of pointer it allocates 2 bytes memory. Because it stores address
of memory location.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int *p1;
char *p2;
float *p3;
double *p4;
clrscr();
printf("\n Size of int pointer:%d bytes", sizeof(p1)); //size of(*)
printf("\n Size of char pointer:%d bytes", sizeof(p2)); //size of(*)
printf("\n Size of float pointer:%d bytes", sizeof(p3)); //size of(*)
printf("\n Size of double pointer:%d bytes", sizeof(p4)); //size of(*)
getch();
}

Pointer arithmetic
Pointer arithmetic actually moves the pointer reference by an arithmetic operation.
i.e. addition and subtraction.
Pointer arithmetic also called as address arithmetic. It allows the following
operations
Valid Pointer arithmetic Operations:-
1) A pointer can be assigned to another. The effect of this operation is to make
the pointers point o the same object.
2) A pointer can be incremented or decremented.
3) Integers can be added or subtracted with pointers i.e; pointer moves forward
or backward directions.
4) Two pointers can be subtracted from one another provided that they are
pointing to the same array.
Invalid Pointer arithmetic Operations:
1. Adding, Multiplying and dividing two pointers
2. Shifting, masking pointers.
3. Addition of float or double to pointers
4. Assignment of a pointer of one type to a pointer of another type.

Pointer arithmetic or scaling factor working

The generalized formula for the addition or subtraction of a constant on a


pointer can be given as
pointer_new_address = (pointer_old_address )
±k*(sizeof(pointer_type))
where k is the constant which is added or subtracted on the pointer, whose
initial address is pointer_old_address
Datatyp Eg Initial Operatio Address Require
e Address n after d bytes
operatio moved
n
int i=2,*p; 4046 ++ 4048 +2
Integer
p=&i;
pointer
int i=2,*p; 4046 -- 4044 -2
p=&i;
char c=’a’,*p; 4146 ++ 4147 +1
Characte
p=&c;
r pointer
char c=’a’,*p; 4146 -- 4145 -1
p=&c;
float f=3.14,*p; 4246 ++ 4250 +4
float p=&f;
pointer
float f=3.14,*p; 4246 -- 4242 -4
p=&f;
double d=3.14,*p; 4346 ++ 4354 +8
double
p=&f;
pointer
double d=3.14,*p; 4346 -- 4338 -8
p=&f;

Pointer arithmetic is very useful when dealing with arrays.

POINTERS AND ARRAYS

When an array is declared, the compiler allocates a BASE address and


sufficient amount of storage which contains all the elements of array in continuous
memory allocation.
The base address is the location of the first element (index 0 of the array).The
compiler also defines the array name as a constant pointer pointed to the first
element.

suppose we declare an array 'a' as follows.


Example:- int a[5]={1,2,3,4,5};
Suppose the base address of a is 1000 and assuming that each integer requires 2
bytes. Then the 5 elements will be stored as follows.

Elements------> a[0] a[1] a[2] a[3] a[4]


------------------------------
values-------> 1 2 3 4 5
-----------------------------
address------> 1000 1002 1004 1006 1008

base address

Here 'a' is a pointer that points to the first element. so the value of a is 1000
there fore a=&a[0]=1000
If we declare 'p' is an integer pointer, then we can make the pointer p
to point to the array 'a' by the following assignment.

int *p;
p=&a[0]; // equal to p=a;

Now we can access every value of a using p++(or)p+1 to move one element to
another.
The relationship between p and a is shown below.
p+0 = &a[0]=1000//1000+0
p+1 = &a[1]=1002//1000+1*(sizeof(int))
p+2 = &a[2]=1004//1000+2*(sizeof(int))
p+3 = &a[3]=1006//1000+3*(sizeof(int))
p+4 = &a[4]=1008//1000+4*(sizeof(int))

When handling arrays instead of using array indexing, we can use pointer to
access array elements. Note that *(p+k) gives the value of a[k]. Pointer accessing
method is much faster than array indexing.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
int *p=a;
clrscr();
printf("a[0]=%u",&a[0]);
printf("\na=%u",a);
printf("\n&a[0]=%u",p);
getch();
}

Program: Write a program to accept and display array elements using pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i;
int *p=&a[0];
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
printf("Given array elements:");
for(i=0;i<n;i++)
{
printf("%5d",*(p+i));
}
getch();
}

POINTER TO A POINTER
A pointer ‘p1′ can also point to another pointer ‘p2′ of same datatype
which is called as pointer to pointer. In memory, the three variables can be
visualized as :

example :
#include<stdio.h>

int main(void)
{
char **ptr = NULL;
char *p = NULL;
char c = 'd';
p = &c;
ptr = &p;
printf("\n c = [%c]\n",c);
printf("\n *p = [%c]\n",*p);
printf("\n **ptr = [%c]\n",**ptr);
return 0;
}
Character Pointers , Pointers and Strings
A string constant, written as
"I am a string"
is an array of characters. In the internal representation, the array is terminated with
the null character ’\0’ so that programs can find the end. The length in storage is
thus one more than the number of characters between the double quotes.
If pmessage is declared as
char *pmessage;
pmessage = "now is the time";
assigns to pmessage a pointer to the character array. This is not a string copy; only
pointers are involved.
char amessage[] = "now is the time"; /* an array */
char *pmessage = "now is the time"; /* a pointer */
amessage is an array, just big enough to hold the sequence of characters and ’\0’
that initializes it. On the other hand, pmessage is a pointer, initialized to point to a
string constant.
Suppose we wish to store “HELLO”.
Different ways are shown below:
char str[ ] = "HELLO" ;
char *p = "HELLO" ;
There is a difference in usage of these two forms. For example, we cannot assign a
string to another, whereas, we can assign a char pointer to another char pointer.
This is shown in the following program.

Example
main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
Also, once a string has been defined it cannot be initialized to another set of
characters. Unlike strings, such an operation is perfectly valid with char pointers.
main( )
{
char str1[ ] = "Hello" ;
char *p = "Hello" ;
str1 = "Bye" ; /* error */
p = "Bye" ; /* works */
}

Unlike other pointers, character pointers doesn’t require indirection operator (*) to
access the value at the address stored in the pointer. We can directly use the name
of the pointer to access the value.

VOID POINTER
 Void pointer can point to any type of data.
 A pointer which can be assigned to any type of pointer is called a void
pointer.
 It is also called as generic pointer.
 Type casting of the void pointer to the required type is essential to access the
data which it points to.

Example program
#include<stdio.h>
#include<conio.h>
void main()
{
void *p;
int i=5;
char c='a';
float f=3.14;
clrscr();
p=&i;
printf("\nValue at address stored in p is %d",*(int *)p);
p=&c;
printf("\nValue at address stored in p is %c",*(char *)p);
p=&f;
printf("\nValue at address stored in p is %f",*(float *)p);
getch();
}

OUTPUT:
Value at address stored in p is 5
Value at address stored in p is a
Value at address stored in p is 3.14

DYNAMIC MEMORY ALLOCATION

Definition:-The process of allocating memory at run time is known as Dynamic


memory allocation.

 Memory Management Functions help to allocate or free the memory during


program execution(Dynamic memory allocation).
 The header file alloc.h contains these memory management functions and
are listed below.

Funcion Task
malloc Allocates requested size of bytes and returns a pointer to the first
byte of the allocated space.
calloc Allocates space for requested array of elements, and returns a
pointer to the first byte of the allocated space.
realloc Modifies the size of previously allocated space.
free Frees previously allocated space.

malloc():-
A block of memory of specified size may be allocated and a void pointer is returned
by using this function.
This void pointer can be assigned to any type of pointer.
Syntax:- ptr=(cast_type *)malloc(byte_size);
ptr is pointer of type cast_type. Byte_size is requested memory space for
allocation in bytes.
Example:- int *p;
p=(int *)malloc(sizeof(int)); //for 1 location
p=(int *)malloc(n*sizeof(int)); //for n locations

calloc():-
Allocates multiple blocks of memory such as arrays, structures, etc. and returns a
void pointer with the address of the first byte location.
Syntax: :- ptr=(cast_type *)calloc(n, element_size);
ptr is pointer of type cast_type. element_size is size of requested type. n is
no. of the elements of the required type.

Example:- int *p;


p=(int *)calloc(n, sizeof(int)); //for n locations

NOTE:- Calloc allocates a block (n times*size)bytes and clears into 0.

Difference between malloc and calloc:


1. malloc allocates single block of storage space whereas calloc allocates
multiple blocks of storage space.
2. malloc defaultly store garbage value where as calloc defaultly stores zero
3. In malloc only one argurment we will pass where as in calloc we will pass two
arguments
realloc():-

 Sometimes it is required to change the allocated memory size.


 realloc alters the size of the already allocated block.

ptr=(cast_type *)realloc(ptr, new_size);

eg:
int *p;
p=(int *)malloc(sizeof(int)); //for 1 location
p=(int *)realloc(p,5*sizeof(int));

Note: Memory allocation may fail and in such cases a null pointer is returned and in
case of realloc if it is unsuccessful, the original block is lost.

free:
Releases the allocated unused space can be done by using free() function.
Syntax: free(ptr);
Example:
free(ptr);

Program:Write a program to create a dynamic array (vector) store values


from keyboard display
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int *a,n,i;
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
a=(int *)malloc(n* sizeof(int));
//a=(int *)calloc(n,sizeof(int));
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",a+i);
}
printf("Given array elements:");
for(i=0;i<n;i++)
{
printf("%d\t",*(a+i));
}
free(a);
getch();
}

Program:Write a program to demonstrate reaolloc


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<string.h>
void main()
{
char *str;
clrscr();
str=(char *)malloc(8);
strcpy(str,"Hello");
printf("String is %s",str);
str=(char *)realloc(str,25);
strcat(str," demonstration of realloc");
printf("\n New string is %s",str);
free(str);
getch();
}

Command-line arguments
The C language provides a method to pass parameters to the main() function. This
is typically accomplished by specifying arguments on the operating system
command line (console).
The prototype for main() looks like:
void main(int argc, char *argv[])
{

}
There are two parameters passed to main().
 The first parameter is the number of items on the command line (int argc).
 The second parameter passed to main() is an array of pointers to the
character strings containing each argument (char *argv[]).
For example, at the command prompt:
test_prog 1 apple orange 4096.0
There are 5 items on the command line, so the operating system will set argc=5 .
The parameter argv is a pointer to an array of pointers to strings of characters, such
that:
argv[0] is a pointer to the string “test_prog”
argv[1] is a pointer to the string “1”
argv[2] is a pointer to the string “apple”
argv[3] is a pointer to the string “orange”
argv[4] is a pointer to the string “4096.0”
and argc is 5

Example program for Command line arguments


#include <stdio.h>

void main(int argc, char *argv[])


{
if ( argc != 3)
{
printf("\nPlease enter arguments properly\n");
exit(0);
}
else
{
printf("\n The areguments given %s %s\n", argv[1],
argv[2]);
}
}

Explanation
line 4 : we check if the user passed two arguments to the program. We actually
need two arguments but in C the first argument ( argv[0] ) is the name of our
program, so we need two more.
line 5 : If the user didn't pass two arguments we print the user to enter arguments
properly and exit.
line 10 : We display the arguments entered by user.

C program prints the number and all arguments which are passed to it.
#include <stdio.h>
void main(int argc, char *argv[])
{
int c;
printf("Number of command line arguments passed: %d\n", argc);

for ( c = 0 ; c < argc ; c++)


printf("%d. Command line argument passed is %s\n", c+1,argv[c]);

}
Dangling Memory / Dangling Pointers
Dangling pointers arise when an object is deleted or deallocated, without modifying
the value of the pointer, so that the pointer still points to the memory location of
the deallocated memory.
The pointer still points to the same location in memory even though the reference
has since been deleted and may now be used for other purposes.

A straightforward example is shown below:


{
char *dp = NULL;
/* ... */
{
char c;
dp = &c;
} /* c falls out of scope */
/* dp is now a dangling pointer */
}
If the operating system is able to detect run-time references to null pointers, a
solution to the above is to assign 0 (null) to dp immediately before the inner block is
exited. Another solution would be to somehow guarantee dp is not used again
without further initialization.
Another frequent source of dangling pointers is a jumbled combination of malloc()
and free() library calls: a pointer becomes dangling when the block of memory it
points to is freed. As with the previous example one way to avoid this is to make
sure to reset the pointer to null after freeing its reference—as demonstrated below.

//Avoiding dangling pointers


#include <stdlib.h>

void func()
{
char *dp = malloc(A_CONST);
/* ... */
free(dp); /* dp now becomes a dangling pointer */
dp = NULL; /* dp is no longer dangling */
/* ... */
}

Write a C Program to reverse a string using pointers


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *s1;
clrscr();
printf("Enter a string\n");
gets(s1);
strrev(s1);
printf("\n The reverse of the given string is %s",s1);
getch();
}
OUTPUT
Enter a string
Hello
The reverse of the given string is olleH

Write a C Program to compare two arrays using pointers


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int *a1,*a2,i,n1,n2,flag=0;
clrscr();
printf("Enter no. of elements in array 1\n");
scanf("%d",&n1);
printf("Enter no. of elements in array 2\n");
scanf("%d",&n2);
if(n1!=n2)
{
printf("\n No. of array elements are not same.");
getch();
return;
}
a1=(int *)malloc(n1*sizeof(int));
a2=(int *)malloc(n2*sizeof(int));
printf("\nEnter %d elements in array 1\n",n1);
for(i=0;i<n1;i++)
scanf("%d",a1+i);
printf("\nEnter %d elements in array 2\n",n2);
for(i=0;i<n2;i++)
scanf("%d",a2+i);
for(i=0;i<n1;i++)
{
if(*(a1+i)!=*(a2+i))
{
flag=1;
break;
}
}
if(flag==0)
printf("\nBoth arrays are equal");
else
printf("\nThe arrays differ at %d position",i+1);
getch();
}
OUTPUT
Enter no. of elements in array 1
3
Enter no. of elements in array 2
3
Enter 3 elements in array 1
123
Enter 3 elements in array 2
124
The arrays differ at 3 position

OUTPUT

Enter no. of elements in array 1


3
Enter no. of elements in array 2
3
Enter 3 elements in array 1
123
Enter 3 elements in array 2
123
Both arrays are equal

OUTPUT

Enter no. of elements in array 1


3
Enter no. of elements in array 2
4
No. of array elements are not same.

UNIT V
ENUMERATED, STRUCTURE AND UNION TYPES

 Arrays are used to store similar type of elements, whereas structures are
used to store different type of data items.
 A structure is a collection of one or more variables, possibly of different
types, grouped together under a single name for convenient handling.
 Using structures we can define our own data type. So structures are also
called as user defined datatype.

Structure Definition:
Structures must be defined first, for their format i.e. template which can be later
used to declare structure variables.
Syntax:
struct tag_name
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
};
For example:
struct emp_info
{
int emp_id;
char nm[30];
int age;
float sal;
};

Note the above example structure emp_info is not declaring any structure variable;
it is just a template to represent information as below.

Integer
Array of 30 Characters
Integer
Float

In defining a structure you may note the following syntax:


 Template is terminated with a semicolon.
 While the entire definition is considered as a statement, each member is
declared independently for its name and type in a separate statement inside
the template(like sub statements)
 The tag name such as emp_info can be used to declare structure variables of
its type later.

Structure Declaration:
we can declare structure variables of that type. Declaration includes the following
elements:
 The keyword “struct”.
 The structure tag name.
 List of variable names separated by commas.
 A terminating semi colon.

Syntax:

struct tag_name structure_var_name1,…,structure_var_namen;


struct is a keyword and tag_name is the tag name specified in its definition.

For Example:
struct emp_info e1,e2,…en;

In this example n structure variables (employees) are created of structure emp_info.


Here for every employee, it has an emp_id,name, age,sal as members.

A structure variable can also be declared along with its definition as shown below
Syntax:
struct tag_name
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
} structure_var_name1;

Example:
struct emp_info
{
char emp_id[10];
char nm[30];
int age;
float sal;
}e1,e2;

Tag name is optional also.

Syntax:
struct
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
}structure_var_ name1,structure_var_name2,…,structure_var_namen;

For example:

struct
{
char emp_id[10];
char nm[30];
int age;
float sal;
} e1,e2,…en;

In the presence of the tag_name also, we can declare structure variables .


Syntax:
struct tag_name
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
}structure_var_ name1,structure_var_name2,…,structure_var_namen;

For example:
struct emp_info
{
char emp_id[10];
char nm[30];
int age;
float sal;
} e1,e2,…en;

Structure Initialization:
A structure can be initialized by following its definition
Syntax:
struct tag_name svar={val1,val2,….,valn};
Example:
struct emp_info e1={1,”Ram”,22,30000};
Such initialization of structure variable is possible along with declaration during
definition also.
Syntax:
struct tag_name
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
}structure_var_ name1={val1,val2,….,valn};

For example:
struct emp_info
{
int emp_id;
char nm[30];
int age;
float sal;
} e1={1,”Ram”,22,30000};

Accessing Structure Members:


 To access the individual members of a structure variable, we need to use the
structure variable as well as period operator dot( .).
 This operator is also called as member operator or dot operator.
Eg:
In the above example, we can access member of e1 as below.
[Link]=1;
strcpy([Link],”Ram”);
[Link]=22;
[Link]=30000;

Copying and Comparing Structure Variables:

Two structure variables of same type can be copied the same way as ordinary
variables.
If s_var1 and s_var2 are structure variables of same type then s_var2 can be
assigned to s_var1 as follows.

s_var1=s_var2; //valid

Similarly two structure variables can also be checked directly for equality or
inequality.

Equality: s_var1==s_var2 //valid


Inequality: s_var1!=s_var2 //valid

These are the only operations which are permitted directly on the structure
variables.

Array of Structures:

We can create an array of structure variables as shown below.

Syntax:

struct tag_name s_var[size];

Example:

struct emp_info e[10];

Here every dataitem of the array is a structure member.


e[0] e[1] e[2] e[3] e[4] e[5] e[6] e[7] e[8] e[9]

Elements of the array are accessed through the index.

e[0].id=1;
strcpy(e[0].name,”Ram”);
e[0].age=22;
e[0].sal=30000;

Arrays in structures or Arrays within Structure

We can use arrays as structure member.


Example:
struct student_marks
{
int roll_no;
int sub[3];
}s;

s.roll_no=1;
[Link][0]=90;
[Link][1]=90;
[Link][2]=95;

Nested Structures or Structures within Structures:


When a structure is declared as the member of another structure, it is called
Structure within a structure. It is also known as nested structure.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;

struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}inner_struct_var;
}outer_struct_var;

Example :

struct student
{
int rno;
char nm[50];
struct
{
int dd;
int mm;
int yyyy;
}dob;
}s;

The members which are inside the inner structure can be accessed as follow :
[Link];
[Link];
[Link];

Structures and Functions

Structures can be passed to or returned from functions.


When a function returns a structure variable its return type should be defined as
structure type along with the appropriate tag.

struct tag_name as return type.

When a structure is passed in a function, we need to pass only the structure


variable as an actual argument and in the function definition (and prototype), we
use struct tag_name as type for formal paramneters.

return_type function_name(struct tag_name s_var);

The following program demonstrates the use of structures and functions


#include<stdio.h>
#include<conio.h>
typedef struct
{
int rl;
int img;
}cno;
cno read_complex_no();
void print_complex_no(cno);
cno add_complex_no(cno a, cno b);
cno multiply_complex_no(cno a,cno b);
void main()
{
cno x,y,res;
clrscr();
x=read_complex_no();
y=read_complex_no();
printf("\n The given complex nos are....\n");
print_complex_no(x);
print_complex_no(y);
res=add_complex_no(x,y);
printf("\n The result of addition of the two given complex nos. is ...\n");
print_complex_no(res);
res=multiply_complex_no(x,y);
printf("\n The result of multiplication of the two given complex nos. is ...\n");
print_complex_no(res);
getch();
}

cno read_complex_no()
{
cno a;
printf("\n Enter real and imaginary parts of the complex no.s\n");
scanf("%d%d",&[Link],&[Link]);
return a;
}

void print_complex_no(cno a)
{
printf("\n %d+i%d\n",[Link],[Link]);
}

cno add_complex_no(cno a, cno b)


{
cno c;
[Link]=[Link]+[Link];
[Link]=[Link]+[Link];
return c;
}

cno multiply_complex_no(cno a,cno b)


{
cno c;
[Link]=[Link]*[Link] -[Link]*[Link];
[Link]=[Link]*[Link]+[Link]*[Link];
return c;
}
Pointers to structures:
Pointers in C are general; we can have pointers to any type.
struct tag_name *ptr_name;

This pointer can point only to the specified structure variable.

struct tag_name s_var;

ptr_name=&s_var;

The members of the structure variable can be accessed through the pointing
pointer also. For this we need a special operator called “arrow operator” ->.

ptr_name->member1=val1;
ptr_name->member2=val2;
.
.
.
ptr_name->membern=valn;

We can also use a traditional model of indirection operator for this


pointer.
(*ptr_name).member1=val1;
(*ptr_name).member2=val2;
.
.
.
(*ptr_name).membern=valn;

The paranthesis are required around *ptr, because period operator is more priority
than indirection operator.

Self-referential structures:

A structure in which a member is a pointer which points to the similar type of


structure is called as self-referntial structure.

Syntax:

struct tag_name
{
type member1;
type member2;
.
.
type membern;
struct tag_name *next;
};
struct node
{
int data; /* points to the data */
struct node *next; /* next data item */
};

struct node n1,n2;

[Link]=10;
[Link]=20;

[Link]=&n2;

It is illegal for a structure to contain an instance of itself, but struct node *next;
declares next to be a pointer to a node type, not a node itself.

The self- referential structures are used in creating various data structures. For
example: linked lists, trees, graphs etc.

Size of a Structure:
The size of the structure is the total size occupied by the individual membes of the
structure.
The size of structure can be found directly by using the sizeof operator over its
type.
struct tagname s_var;
sizeof(struct tagname); gives the size occupied by any structure variable of this
type
or
sizeof(s_var); gives the size occupied by the structure variable

Example:
struct emp_info
{
int id;
char name[100];
int age;
float sal;
};
struct emp_info e1;
sizeof(struct emp_info) gives 108 (2+100+2+4) bytes.
sizeof(e1) is also same.
Unions:
Unions are a concept borrowed from structures.
The syntax of unions is same as structures. The major difference between structure
and union is in terms of storage.

Syntax of union

union tag_name
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
};

union tag_name u_var;

This declares a union variable. “union” is a keyword.

Example:
union item
{
int m;
float x;
char c;
}code;

1000 1001 1002 1003

Integer ‘m’ uses only two bytes

charcater ‘c’ uses only one byte

float x uses all four bytes


Syntactically, members of a union are accessed as
union_var.member
or
union_pointer->member
just like structures.

Program on unions

#include<stdio.h>
#include<conio.h>
typedef union
{
int a;
float b;
char c;
} utype;
void main()
{
utype u1={10};
clrscr();
printf("\n u1.a is %d\n",u1.a);
u1.b=3.14;
printf("\n u1.b is %f\n",u1.b);
u1.c='a';
printf("\n u1.c is %c\n",u1.c);
printf("\n The size of union u1 is %d",sizeof(u1));
getch();
}

Size of Unions:

The size of union is the size of the highest memory required among all its members.
In the above example code, the size of union is 4 bytes as float is the highest
memory required member among all the union members. This can be obtained by
the size of operator.

sizeof(code);
or sizeof(union tag_name);

Alternative naming of types:


typedef:
typedef is a keyword in the C programming language. The purpose of typedef is to
assign alternative names to existing types.
Syntax:

typedef type newname;


 By using typedef we can assign a new alternative name to the existing type.
 Both the standard predefined type name and alternative new name can be
used for declaring variables.

Example:
typedef int integer;
int x;
integer y;
Both x and y are integers.

Bit-Fields:

A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length. A
word (16bits here) can therefore be divided into a no. of bit fields. The name and
size of bit fields are defined using a structure.
The general form of bit field definition is

struct tag_name
{
datatype name1: bit_length;
datatype name2: bit_length;
.....
.....
datatype nameN: bit_length;
};

Several points to be observed:

 The datatype can be either int or unsigned int and the bit_length is the no. of
bits used for the specified name.
 int or signed int must have bit_length atleast 2. One bit is dedicated for sign.
 Field name is followed by the colon.
 The bit_length is decided by range of value to be stored.
 The largest value that can be stored is 2 n-1 , where n is bit_length. We have to
assign values within the bitfield’s range, else it gives unpredicated behaviour.
 He first field always starts with the firt bit of the word.
 A bit field cannot cross the integer storage boundary. That means the sum of
bit_lengths of all the bit fields cannot exceed 16.
 There can be unnamed fields used for padding
 There can be unused bits in a word.
 We cannot obtain address of a bit field.
 So, we cannot use scanf to read values to bit fields.
 We cannot refer pointers to bit fields.
 Bitfields cannot be arryed.

Example:

Struct personal
{
unsigned gender : 1
unsigned age : 7
unsigned m_status : 1
unsigned children : 3
unsigned : 4
} emp;

Bit field Bit length Range of value


gender 1 0 to 1
age 7 0 to 127 (27-1)
m_status 1 0 to 1
Children 3 0 to 7 (23-1)

Once bit fields are defined, they can be accessed just like other structure members.

Example:

[Link]=1;
[Link]=30;
emp.m_status=0;
[Link]=0;

Its valid to combine normal structure members with bit field elements.

For example:

struct emp_info
{
int id;
char name[20];
unsigned age : 7;
unsigned gender : 1;
float sal;
};

Enumerated Datatype:
Enumerated datatype is a user –defined datatype in which enum keyword is
treated as type and used to declare variables that can have one of its enumeration
constants.

Syntax:
enum tag_name
{
val1;
val2;
.
.
valn;
};

enum etype {val1,val2,…..,valn};


etype enum_variable1,enum_variable2,….,enum_variablen;
For Example:

enum day { Mon=3,Tue,Wed,Thurs,Fri,Sat,Sun};

Here Mon is assigned a value 3 and then remaining constants are assigned values
which increase by 1 successively.

We can assign different values to enumerated constants instead of sequential


values. For that we need to assign each a specific value.

enum day { Mon=3,Tue=10,Wed=5,Thurs=8,Fri=7,Sat=1,Sun=4};

In the enumerated type definition, if the enumeration constants are not assigned
any integers, then they will be automatically assigned a value which is +1 to the
value assigned to the previous enumeration constant and if the initial constant are
not assigned anything, then 0 is assigned.

enum day { Mon, Tue, Wed=5,Thurs=8,Fri,Sat,Sun=4};

The definition and declarartion of enumerated variables can be combined in one


statement as shown.
enum day {Mon,Tue,Wed,Thurs,Fri,Sat,Sun} d1,d2;
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
enum day { Mon,Tues,Wed,Thurs,Fri,Sat,Sun};
enum day d1,d2;
clrscr();
printf("\n Mon is %d\n",Mon);
printf("\n Thurs is %d\n",Thurs);
printf("\n Sat is %d\n",Sat);
printf("\n Sun is %d\n",Sun);
d1=5;
d2=Sat;
printf("\n d1:%d\t d2:%d\n",d1,d2);
getch();
}
Output:
Mon is 0
Thurs is 3
Sat is 5
Sun is 6
d1:5 d2:5

Differences between Arrays and Structures


Both arrays and structures are collection of datatypes, but there are remarkable
differences between them.

Arrays Structures
1. An array is a collection of 1. Structure can have elements of
related data elements of same different types
type.
2. An array is a derived data 2. A structure is a programmer-
type defined or user-defined data type
3. Any array behaves like a 3. But in the case of structure,
built-in data types. All we have first we have to design(definition)
to do is to declare an array and declare a data structure
variable and use it. before the variable of that type
are declared and used.
Array elements are -. Structure elements are
homogeneous heterogeneous
Array allocates static memory Structures allocate dynamic
and uses index / subscript for memory and uses (.) operator for
accessing elements of the accessing the member of a
array. structure.
Array is a pointer to the first Structure is not a pointer
element of it
Array elements takes less time Structure members takes more
to access. time to access in comparison
with arrays.

Differences between Structures and Unions:


Structure Union
[Link] keyword struct is used to define a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a 2. When a variable is associated with a
structure, the compiler allocates the union, the compiler allocates
memory for each member. The size of the memory by considering the size of
structure is greater than or equal to the the largest memory. So, size of union is
sum of sizes of its members. The smaller equal to the size of largest member.
members may end with unused slack
bytes.
3. Each member within a structure is 3. Memory allocated is shared by
assigned unique storage area of location. individual members of union.
4. The address of each member will be in 4. The address is same for all the
ascending order This indicates that members of a union. This indicates that
memory for each member will start at every member begins at the same offset
different offset values. value.
5 Altering the value of a member will not 5. Altering the value of any of the
affect other members of the structure. member will alter other member values.
6. Individual member can be accessed at 6. Only one member can be accessed at
a time a time.
7. Several members of a structure can 7. Only the first member of a union can
initialize at once. be initialized.

FILE HANDLING

File Handling: Input and Output – Concept of a file, text files and binary files,
Formatted I/O, File I/O operations, Example Programs
Introduction to Files
Most programs have Input or output or both the operations. They are performed
using devices like keyboard, printer, monitor, etc attached to computer. To perform
I/O in a device independent form, C treats each of them in the same way, as a file.
Thus file can be read or written repeatedly from a permanent storage like
disk file or a stream of bytes received from or sent to a peripheral device
(keyboard, monitor, etc). The first one is called disk file. The second model of file
is called a device file or interactive file as it deals with device and user interactions.

Types of Files
Depending on the contents of the files, they are categorized as text files and
binary files. Text files require text streams and binary files require binary
streams as discussed above.

Depending on the file data accessing, they are categorized into two types.
 Sequential access file
 Random access file

Sequential access file: We can access data sequentially only. Data can be
accessed only if the data before it is accessed.

Random access file: Data can be accessed randomly. Data can be


accessed directly without interfering with the data before it.

Operations on Streams(Files)
FILE is a type which deals with file streams. The operations on files can be
categorized into three major types.

 Opening
 Reading/Writing
 Closing

Opening a stream(file)
To perform any operation on a file, it must be first opened. The file can be
opened by using the function fopen.

FILE *fp=fopen(“filename”,”opening mode”);


For example

FILE *fp=fopen(“[Link]”,”r”);

FILE *fp;
fp=fopen(“c:\fed\[Link]”,”w”);
A text file abc is (.txt is extension in [Link]) opened in read
mode.

 The function fopen creates a new stream and establishes a connection


between the file and the stream.
 The fopen is declared in the header file stdio.h
 The fopen requires two arguments. The first one is the file name and
the second one is the opening mode.
 Filename generally includes the file extension also. Extension indicates
the type of the file. Path indicating the exact location of the file is
necessary if file is not in the same directory as the program (current
working directory).
 Opening mode of the file gives the information about what type of
operation is performed on the data, like read, write or both etc.
 On successful opening of the file, the fopen returns a pointer of type
FILE and on failure it returns a NULL pointer.
 The most common reasons for failure are
o Opening a file with read mode when the file does not existing.
o Creating files when disk is write protected or not enough space.

 Various modes for opening a file and their purpose are specified below.

Mode Description
Closing a stream:

An open stream can be closed by using function fclose. The fclose is also declared
in stdio.h

fclose(FILE *stream);

Example: fclose(fp);

 If fclose is successful, then the stream passed as argument and associated


stream are closed.
 Before closing the stream, any unwritten data present in the stream buffer
are written to the file, but the unread data is discarded.
 The link between the stream and the file are broken. Returns 0 on success
and EOF on failure.
 fclose can close even standard streams.
The function fclose closes a specific stream. If there are number of streams, need to
be closed, then fcloseall() can be used.

flcoseall();

 fcloseall closes all the open streams and the corresponding files.
 fcloseall doesn’t close standard streams.

#include<stdio.h>
main()
{
FILE *fp;
fp = fopen("[Link]", "w");//if file does not exist file will be
created
if (fp == NULL)
{
printf("File does not exist,please check!\n");
}
fclose(fp);
}

Reading/Writing Files - I/O with Files

Input, Output operations on files, can be performed by using formatted or


unformatted functions.

The unformatted I/O operation can be characterized as

 Character I/O
 Line I/O
 Block I/O

Character I/O

Character Input:

The fgetc and getc functions read a character from the input file referenced by fp
in argument. The return value is the character read, or in case of any error it
returns EOF. After reading a character, the file stream automatically moves to the
next character in the file. Both these functions are defined in stdio.h.

Syntax:

fgetc( FILE * fp ); getc( FILE * fp );

ch=fgetc(fp); ch=getc(fp);

Character Output:
The fputc and putc are functions to write a character to the file referenced by fp.
These functions takes two parameters, first one the character to be read and
second the fp. Both these functions are defined in stdio.h.

Syntax:

fputc(char ch, FILE * fp ); fputc(ch,fp);

putc(ch,fp); putc(ch,fp);

fputc(char ch, FILE * fp );

#include<stdio.h>
main()
{
FILE *f1;
printf(“Data input output”);
f1=fopen(“[Link]”,”w”); /*Open the file Input in write mode*/
while((c=getchar())!=EOF) /*get a character from key board*/
fputc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“nData outputn”);
f1=fopen(“[Link]”,”r”); /*Reopen the file input*/
while((c=fgetc(f1))!=EOF) /*EOF-END OF FILE*/
printf(“%c”,c);
fclose(f1);
}

Formatted I/O

The fprintf and fscanf functions are identical to printf and scanf functions except
that they work on files. The first argument of theses functions is a file pointer which
specifies the file to be used. The general form of fprintf is
fprintf(fp,”control string”, list);

Where fp Is a file pointer associated with a file that has been opened for writing. The
control string is file output specifications list may include variable, constant and
string.

fprintf(f1,”%s%d%f”,name,age,7.5);

Here name is an array variable of type char and age is an int variable
The general format of fscanf is

fscanf(fp,”controlstring”,list);

This statement would cause the reading of items in the control string.

Example:

fscanf(f2,”%s%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 num,qty,I;
float price,value;
char item[10],filename[10];
printf(“Input filename”); /*[Link]*/
scanf(“%s”,filename);
fp=fopen(filename,”w”);
printf(“Input inventory datann”);
printf(“Item namem number price quantityn”);
for(I=1;I< =3;I++)
{
fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quantity);
fprintf(fp,”%s%d%f%d”,item,number,price,quantity);
}
fclose (fp);
fp=fopen(filename,”r”);
printf(“Item name number price quantity value”);
for(I=1;I< =3;I++)
{
fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quantity);
value=price*quantity;
fprintf(stdout,”%s%d%f%d%dn”,item,number,price,quantity,value);
}
fclose(fp);
}

File Position Indicator

The file position of a stream describes where in the file the stream is currently
reading or writing. I/O on the stream advances the file position through the file.

 The file position is represented as a long integer, which counts the number of
bytes from the beginning of the file.
 The initial value of file position indicator depends upon the mode in which the
file is opened. If the file is opened in read/write mode, the file position
indicator is at the beginning of the file and will have value zero. If the file is
opened in append mode, the initial value of the file position indicator is at
last.
 As calls are made to read or write to a file, file position indicator is moved.

The current location of the file position indicator for the stream can be
determined by using the functions ftell and fgetpos.

Function ftell() returns the current position of the file pointer in a stream. The return
value is 0 or a positive integer indicating the byte offset from the beginning of an
open file. A return value of -1L indicates an error. Prototype of this function is as
shown below:

long int ftell(FILE *fp);

example: long int pos;


pos=ftell(fp);

Function fgetpos() gets the current value of the file position indicator for the stream
in first argument and stores in second argument.

fgetpos(FILE *fp, long int *pos)


example:

long int pos;


fgetpos(fp,&pos);

Non-Sequential file accessing


Generally files are accessed sequentially. With this we can access an element in a
file only when the previous data is accessed. When we need to access a particular
element directly, then fseek and fsetpos are useful

fseek()

This function positions the next I/O operation on an open stream to a new position
relative to the current position.

int fseek(FILE *fp, long int offset, int origin);

Here fp is the file pointer of the stream on which I/O operations are carried
on, offset is the number of bytes to move. The offset can be positive or negative,
positive when moving forward and negative for backward movement in the
file. Origin is the position in the stream to which the offset is applied, this can be
one of the following constants:

Origin/Whence Integer Decription Possible offset


value sign
SEEK_SET 0 offset is relative to beginning Positive – only
of the file forward movement

SEEK_CUR 1 offset is relative to the Both Positive &


current position in the file negative – forward
& backward
movements
respectively.
SEEK_END 2 offset is relative to end of the Negative – only
file backward
movement
fsetpos is a function to set the file position in file stream (first argument) to the
position indicated in second argument.
fsetpos(FILE *fp, long int *pos)
rewind() is used to reset the position to the beginning of the file.
rewind(FILE *fp)
example:
rewind(fp);
It returns no value. It is equivalent to fseek(fp,0,SEEK_SET);

End of File and Errors


EOF is the file ending position indicator. Every character read must be tested
whether it is end of file or not. We have a function feof which serves this purpose.
This tests the end-of-file indicator for the given stream.
Prototype:
int feof(FILE *stream)
Parameters
 stream − This is the pointer to a FILE object that identifies the stream.
Return Value
This function returns a non-zero value when End-of-File indicator associated with
the stream is set, else zero is returned.
Function ferror() tests error indicators for a stream. If there is an error in
associated stream, it returns a non-zero value.

Example
The following example shows the usage of feof() function.
#include <stdio.h>
int main ()
{
FILE *fp;
char c;
fp = fopen("[Link]","r");
if(ferror(fp))
{
printf("Error in opening file");
return(-1);
}
while( !feof(fp))
{
c = fgetc(fp);
printf("%c", c);
}
fclose(fp);
return(0);
}

FILES and Command Line Arguments

The C language provides a method to pass parameters to the main() function. This
is typically accomplished by specifying arguments on the operating system
command line (console).
The prototype for main() looks like:
void main(int argc, char *argv[])
{

}
There are two parameters passed to main(). The first parameter is the number of
items on the command line (int argc). Each argument on the command line is
separated by one or more spaces, and the operating system places each argument
directly into its own null-terminated string. The second parameter passed to main()
is an array of pointers to the character strings containing each argument (char
*argv[]).
For example, at the command prompt:
test_prog 1 apple orange 4096.0
There are 5 items on the command line, so the operating system will set argc=5 .
The parameter argv is a pointer to an array of pointers to strings of characters, such
that:
argv[0] is a pointer to the string “test_prog”
argv[1] is a pointer to the string “1”
argv[2] is a pointer to the string “apple”
argv[3] is a pointer to the string “orange”
argv[4] is a pointer to the string “4096.0”
and argc is 5

Example program for Command line arguments


#include <stdio.h>

void main(int argc, char *argv[])


{
if ( argc != 3)
{
printf("\nPlease enter arguments properly\n");
exit(0);
}
else
{
printf("\n The areguments given %s %s\n", argv[1],
argv[2]);
}
}

File names can be passed through command line arguments.

Write a C program which copies one file to another.


//Make sure file to be read is in same directory

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2;
char ch, *fsrc,*fdest;
clrscr();
printf("Enter the file name to be copied\n");
gets(fsrc);
printf("Enter the file name to paste the copied contents.\n");
gets(fdest);
fp1=fopen(fsrc,"r");
fp2=fopen(fdest,"w");
if(ferror(fp1))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,fp2);

}
fcloseall();
fp2=fopen(fdest,"r");
printf("\nThe contents copied from the given file are ...\n");
while(!feof(fp2))
{
ch=getc(fp2);
putc(ch,stdout);

}
fclose(fp2);
getch();

}
OUTPUT:
Enter the file name to be read copied
[Link]
Enter the file name to paste the copied contents.
[Link]
The contents copied from the given file are ...
Hello
Hi
This is file handling program coping contents from one file to another.

Write a C program to count the number of characters and number of lines


in a file

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch, *fname;
int nc,nl,nw;
nc=nl=nw=0;
clrscr();
printf("Enter the file name\n");
gets(fname);
fp=fopen(fname,"r");
if(ferror(fp))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
printf("\nThe contents of the given file are ...\n");
while(!feof(fp))
{
ch=getc(fp);
putc(ch,stdout);
nc++;
if(ch==' ' || ch=='\n')
nw++;
if(ch=='\n')
nl++;
}
printf("\nThe number of characters in the file are :%d\n",nc);
printf("\nThe number of words in the file are :%d\n",nw);
printf("\nThe number of lines in the file are :%d\n",nl);
fcloseall();
getch();
}
OUTPUT:
Enter the file name
[Link]
The contents of the given file are ...
Hello
Hi
This is file handling program coping contents from one file to another.
The number of characters in the file are :63
The number of words in the file are :14
The number of lines in the file are : 3

Write a C program to merge two files into a third file. The names of the
files must be entered using command line arguments.

#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[])
{
FILE *fp1,*fp2;
char ch;
clrscr();
if(argc!=4)
{
printf("\nNot enough arguments are passed. Program halted!!");
getch();
exit(0);
}
fp1=fopen(argv[1],"r");
fp2=fopen(argv[3],"w");
if(ferror(fp1))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
printf("\nThe contents of the given file1 are ...\n");
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,stdout);
putc(ch,fp2);
}
fclose(fp1);
fp1=fopen(argv[2],"r");
if(ferror(fp1))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
printf("\nThe contents of the given file2 are ...\n");
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,stdout);
putc(ch,fp2);
}
fcloseall();
fp1=fopen(argv[3],"r");
if(ferror(fp1))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
printf("\nThe contents of the file3 merged from file1 and file2 are ...\n");
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,stdout);
}
fclose(fp1);
getch();
}

OUTPUT:
The contents of the given file1 are ...
Hello
Hi
This is file handling program merging contents of two files to another.

The contents of the given file 2 are ...


Using command line arguments, file names passed as arguments.

The contents of the file3 merged from file1 and file2 are ...
Hello
Hi
This is file handling program merging contents of two files to another.
Using command line arguments, file names passed as arguments.

You might also like