You are on page 1of 27

Programming using C UNIT-V I SEMESTER B.C.

Pointers

One of the powerful features of ‘C’ is its ability to access the memory
variables by their memory address. This can be achieved through a special type of
variable called pointer.

Definition of Pointer Variable: A pointer is a variable, which holds


address of another variable. A Pointer variable holds physical memory address.

A variable in a program is a symbolic name given to a memory location. The


programmer refers the memory location by its symbolic name. Every memory
location is associated with two distinct values namely address of the memory
location and the contents of the memory location.

Ex: int i=3, this declaration creates memory for variable ‘i’ as shown below.

i  Location name
3  value at location

6488 Location address

Many complex tasks require that a memory location be referred to by its


addresses, rather by its name. Pointers are used to hold the address of the memory
location. Pointers can be used to access data by using its address.

The & and * operators:

The & is the address operator, it represents the address of the variable. This
operator returns the memory address of variable on which it is operated.

Ex: p=&a;
This statement assigns address of the variable ‘a’ to pointer variable ‘p’.

‘*’ is called ‘value at address’ operator. It gives the value stored at a particular
address. The value at address operator is also called ‘indirection’ operator.

Ex: printf(“\n%d”, *p);

This statement displays the data value stored at the address in ‘p’. The * is also used
to declare pointer variable.

Defining a Pointer Variable :

In ‘C’ a pointer variable is declared by preceding its name with an asterisk ‘*’.

Department of Computer Science 1 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

The general form of a pointer declaration is:

data type * variable_name;

* indicates that the variable is a pointer variable. Holds the address of type
data type.

Ex: int *p;

This declares the variable ‘p’ as a pointer variable that points to an integer
data type.

Ex: float *q;

Declares q as a pointer variable which can point float data.

Initialisation of Pointers:
Once a pointer variable has been declared, it can be made point to a variable
using an assignment statement.

Ex: int a;
int *p;
p=&a;
This statements assigns address of variable ‘a’ to integer pointer ‘p’.

A pointer variable can be initialised at the time of declaration.

Ex: int x, *p=&x;

This statement declares a pointer variable p and assigns address of ‘x’ to p.

Ex : Program to illustrate basic Pointers :


#include “stdio.h”
main()
{
int a, *int_ptr;
float b, *float_ptr;
char c, * char_ptr;
a=25;
b=35.95;
c=’/’;
int_ptr=&a;
float_ptr=&b; Assigns address of a, b, c to corresponding pointer
variables
char_ptr=&c;

Department of Computer Science 2 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

printf(“\n%d\t%d”, a, * int_ptr);
printf(“\n%f\t%f”, b, * float_ptr);
printf(“\n%c\t%c”, c, * char_ptr);
getch();
}
This programs gives the following output
25 25
35.95 35.95
/ /

Using Pointers in Expressions:

The value referenced by a pointer can be used in arithmetic expression.


Following example shows use of pointers in arithmetic expressions.

#include “stdio.h”
main()
{
int i1, i2;
int *p1, p2;
i1=5;
p1=&i1;
i2=*p1/2+10;
p2=p1;
printf(“i1=%d, i2=%d, *p1=%d, *p2=%d”, i1,i2,*p1,*p2);
getch();
}

The output of the above program is


i1=5, i2=12, *p1=5, *p2=5

In the above program, the statement


i2=*p1/2+10;
evaluates value at address p1/2 i.e. 5/2=2,
adds it to 10, so i2 becomes 12

Operations on Pointers: The size of the data type to which the pointer variable
refers is the number of bytes of memory accessed when the pointer variable is
dereferenced by using the ‘*’ operator. The size of a pointer variable remains the
same irrespective of the data type to which it is pointing.

1. A pointer to an integer accesses 2 bytes of memory.


2. A pointer to char accesses 1 byte of memory.
3. A pointer to float accesses 4 bytes of memory.
4. A pointer to a double accesses 8 bytes of memory.

Department of Computer Science 3 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

C allows following arithmetic operators on pointers

Unary operators: ++ (increment)


- - (decrement)

Binary operators: + (addition)


- (subtraction)

Ex: int *p;


if p=2075
after p++, p=2077

Ex: float *p2;


if p2=3092
after p2++, p2=3096

Other operations we can perform on pointers are comparing to pointers to see


if they are equal or not, or if one pointer is less than or greater than other pointer.

Understanding computer Memory


A computer’s memory can be viewed as a sequential collection of storage
cells. Each cell of the computer’s memory has a number, called an address,
associated with it. On most computer systems, a ‘cell’ is called byte.

The computer uses memory for storing the instructions of program and also
for storing the values of the variables in the program
Ex : If we declare a variable called ‘count’ of type int, the system assigns locations in
memory to held the value of ‘count’.

int count = 10;


int*int_ptr;
int_ptr=&count;
count
10

int_ptr holds address of count i.e. 500


500

As int_ptr is of type pointer to int, the value stored in the memory given by
*int_ptr is interpreted as an integer by the system.

Department of Computer Science 4 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

The *int_ptr refers the value in the address of int_ptr i.e. the value of the
variable ‘count’.
Pointers and Structures

Pointers can be defined to point to structures. Consider the following


structure definition.
struct date
{
int month;
int day;
int year;
};
struct date todaysdate;

This statement declares a variable todaysdate of type struct date. A Pointer variable
can be defined as
struct date *dateptr;
dateptr = & todaysdate; will set the address of structure ‘todaysdate’ to
‘dateptr’.

 Operator :
The structure pointer operator  which is the dash followed by the greater
than sign, is used to access structure elements using pointer.

Structure elements can be referred as :


dateptr day
dateptr month
dateptr year
These elements can also be accessed as :
*dateptr. day
*dateptr . month
*dateptr . year
Fig. Below shows the pointer to the structure
If dateptr day=25;
dateptr month=1;
dateptr year=2019;

dateptr

. day 25

. month 1

. year 2019

Department of Computer Science 5 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

Ex : Program to illustrate pointer to structure :

# include “stdio.h”
main ()
{
struct emp
{
int eno;
char ename[20];
int deptno;
};
struct emp e;
struct emp *ptr;
ptr=&e;
printf(“\n Enter employee No:”);
scanf(“%d”, &e.eno);
printf(“\n Enter employee Name:”);
scanf(“%s”, &e.ename);
printf(“\n Enter Department No:”);
scanf(“%d”, &e.deptno);
printf(“\n Employee details \n”);
printf(“\n Employee No:%d”, ptreno);
printf(“\n Employee Name :%s”, ptrename);
printf(“\n Department No:%d”, ptrdeptno);
}

In the above program ptr is a pointer to structure ‘e’ of type struct emp. The
structure elements can be refered in both ways like e.eno, e.ename, e.deptno and
ptreno, ptrename, ptrdeptno.

Structures containg Pointers : A Pointer also can be a member of a structure

Ex : struct intptrs
{
int *p1;
int *p2;
};
A structure called ‘intptrs’ is defined to contain two integer pointers, the first
one called p1 and second one p2.

Department of Computer Science 6 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

Ex : Example for structure of integer pointers :

# include “stdio.h”
main()
{
struct intptrs
{
int *p1;
int * p2;
};

struct intptrs point;


int a=100;
int b = 200;
point.p1=&a;
point.p2=&b;
printf(“\n a=%d”, *point.p1) ; Displays value of a
printf(“\n b=%d”, *point.p2) ; Displays value of b
getch();
}

In the above program the statement


struct intpters point; declares ‘point’ as a variable of type struct intptrs. Point
p1 and print.p2 are two integer pointer variables
point.p1=&a; sets p1 member pointing to a and
point.p2=&a; sets p2 member pointing to b

Pointers and Functions: passing Arguments to Functions using Pointers


We can pass a pointer as an argument to a function in the normal fashion, and
we can also have a function return a pointer as its result.
Ex: main ()
{
int a, ptr;
ptr = &a;
.
.
display (ptr);
.
.
}

Department of Computer Science 7 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

In the above example an integer pointer ‘ptr’ is passed as an actual parameter


to the function display (). Inside the display () function, the formal parameter must
be declared to be a pointer to appropriate type.
void display (int * ptr1)
{
…………..
}

The actual parameter ptr valur is assigned to formal parameter ptr2.

Ex : Following example shows the passing of pointers to function :


#include “stdio.h”
void display (float *, float *);
main ()
{
float a,b;
float *ptr1, *ptr2;
a = 75.45;
b = 82.34;
ptr1=&a;
ptr2=&b;
display (ptr1,ptr2);
getch();
}
void display (float *p1, float *p2)
{
printf(“\n value of a = %f”, *p1);
printf(“\n value of b = %f”, *p2);
}
In the above example two float pointers ptr1, ptr2 are passed to the function
display (). The formal parameters in function display are two float pointers p1 and
p2.
Ex : struct emp
{
int eno;
chat ename [20];
}
void display (struct emp*);
main ()
{
struct emp e={25, “billgates”);
struct emp *p;
p=&e;
display (p);
}

Department of Computer Science 8 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

void display (struct emp *p1);


{
printf(“\n eno=%d”, p1eno);
printf(“\n ename=%s”, p2ename);
}
In above example structure pointer ‘P’ of type struct emp is passed and is
received in p of same type.

Call by value and Call by reference:

‘C’ provides two different methods of parameter passing to functions namely


call-by-value and call-by-reference. If a function is called by passing values of
arguments the function calling is called call by value. When parameters are sent by
call-by-value, the called function cannot modify the actual parameters.

Call-by-reference in C, can be achieved by passing address of a parameter. If a


function is called by passing addresses of arguments, then the function calling is
called call-by-reference. An address of a parameter refers a physical location in the
memory and when address of a parameter is passed, the same location can be
referred by the formal parameter. The formal parameters must by pointer variables
so as to store address of the actual parameter.
Ex:- Following programs explains the concept of call by value and call by
reference.

Ex: Call by value

#include “stdio.h”
main()
{
int first, second;
first=100;
second=200;
swap(first, second);
printf(“value of first =%d\t value of second =%d\n”, first, second);
getch();
}
swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}

Department of Computer Science 9 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

since in this program, the parameters are passed to function swap() using call by
value, function swap() can not interchange the values first, second of main()
function.
O/p is value of first=100 value of second = 200

Ex: call-by-reference
#include “stdio.h”
main()
{
int first, second;
first=100;
second=200;
swap(&first, &second);
printf(“The value of first=%d\t The value of second =%d\n”, first, second);
getch();
}
swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Since in this program, the parameters are passed to function swap() using call by
reference, function swap() interchanges the data values.
O/p The value of first = 200 The value of second = 100

Pointers to Functions : In ‘C’ we may have a pointer to a function. When


working with pointers to function, the ‘C’ compiler needs to know not only that the
pointer variable points to a function, but also the type of value returned by that
function as well as the member and type of its arguments.
Ex : To declare a variable ‘fnptr’ to be of type pointer to function that returns an int
and that takes no arguments.

int (*fnptr)(void)
main ()
{
int a;
fnptr = f1;
a=fnptr();
printf(“\n a=%d”, a);
getch();
}

Department of Computer Science 10 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

int f1 (void)
{
int b=10;
return (b);
}
In the program fnptr=f1; assigns address of function f1() to fnptr pointer.
a=fnptr(); calls the function f1() and returns an integer value.
Pointers and Arrays

Arrays can be accessed using pointers. Pointers to arrays uses less memory
and executes faster.
Consider an array ‘value’ of 100 integers.
int value [100];
We can define a pointer variable to access array elements as
int *ptr;

------
value [10] value [1] value [2] value [99]
ptr

The statement
ptr=value; (or)
ptr=&value [0];

Will assign array address i.e. address of first element to ptr. By using
increment operator we can access all elements of an array
Ex : Following example explains accessing of array elements using pointers :

# include “stdio.h”
main ()
{
int a[10], i;
int *p;
p=a; (or) p=&a[0];
printf(“\n Enter Array Elements :”);
for (i=0; i<10;i++)
scanf(“%d”, &a[i]);
for (i=0; i<10;i++,p++)
printf(“\t%d”,*p);

}
getch();
}

Department of Computer Science 11 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

p=a statement assigns address of array i.e. first element address to variable
‘p’. The statement ‘p++’ in loop points to subsequent elements in the array.

Pointers to character strings :

Strings can be accessed with pointers.

char*days [] = {“Sunday”, ”Monday”, “Tuesday”, “Wednesday”, “Thursday”,


“Friday”, “Saturday”};

The above statement declares an array of pointers pointing to corresponding


strings in the declaration.

day [0] S U N D A Y \O

day [1] M O N D A Y \O

day [2] T U E S D A Y \O

day [3] W E D N E S D A Y \O

day [4] T H U R S D A Y \O

day [5] F R I D A Y \O

day [6] S A T U R D A Y \O

Ex : Following example shows accessing character strings using pointers :

main ()
{
chat *name [10];
int i;
printf(“\n Enter Strings :\n”);
for (i=0; i<10;i++)
scanf (“%s” name[i]);
printf(“\n Entered Strings :\n)”;
for (i=0; i<10;i++)
printf(“\n%s”, name[i]);
getch();
}

Department of Computer Science 12 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

In above example char *name [10]; statement can point to 10 strings. The
character strings is assigned and displayed using for loops.

Passing arrays to functions using Pointers :


An array can easily passed to a function by using its pointer.
Ex : main ()
{
int a[50];
int *p1, i,n;
printf(“\n Enter no.of elements :”);
scanf(“%d”,&n);
printf(“\n Enter array elements :”);
for (i=0; i<n;i++)
scanf (“%d” & a[i]);
p1=&a[0];
display (p1,n);
getch();
}
void display (int *p2, int n)
{
int i;
for (i=0; i<n;i++)
{
printf(“\t %d”, * p2);
p2++;
}
}
In the above program array pointer and no.of elements in array are passed to
function display (). In function the arguments are received into formal arguments
(i) an integer pointer (ii) and integer value. The for loop in the function display ()
will access the array elements of array ‘a’ declared in main () using pointers.
Advantages of pointers:
The usage of pointers in the program has following advantages.
1. More than one value from a function can be return using pointers.
2. Arrays and strings are more conveniently passed from one function to
another, using pointers.
3. Pointers are used to create complex data structure, such as linked lists, binary
trees etc.
4. A function can be called by passing variables address instead of variables
data.
5. Pointers speeds up the processing of data
6. Complex operations can be performed using pointers.
7. Pointer concepts are very useful in development of system software.

Department of Computer Science 13 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

8. With the address known, data can be accessed from anywhere in the
program.
9. Pointer to pointer concept is possible.
10. ‘Pointer’ is a powerful tool for ‘C’ programmers in software development.
Drawbacks of pointers:

1. Uninitialized pointers might cause segmentation fault.


2. Dynamically allocated block needs to be freed explicitly. Otherwise, it would
lead to memory leak.
3. Pointers are slower than normal variables.
4. If pointers are updated with incorrect values, it might lead to memory
corruption.
5. Errors due to pointers are difficult to debug.
6. It’s programmer’s responsibility to use pointers effectively and correctly.

NULL pointers
The word "NULL" is a constant in C language and its value is 0.
If any pointer does not contain any valid memory address or any pointer is
uninitialized, known as "NULL pointer".

Ex:
int a=10;
int *ptr1=&a;
int *ptr2;
int *ptr3=0;

In above example ptr1 is initialized with the address of a, thus ptr1


contains a valid memory address. ptr2 is uninitialized and ptr3 assigned 0. Thus,
ptr2 and ptr3 are the NULL pointers.

Use of NULL pointers:


1. To initialize a pointer variable when that pointer variable isn’t assigned any
valid memory address yet.
2. To pass a null pointer to a function argument when we don’t want to pass any
valid memory address.
3. To check for a null pointer before accessing any pointer variable. By doing so,
we can perform error handling in pointer related code.

Memory Allocation in ‘C’ programs

Since C is a structured language, it has some fixed rules for programming. In ‘C’
memory will allocates for different data structures, variables and constants based on
their type.

Department of Computer Science 14 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

For Ex: int a[10];

The above declaration length of the array is 10. If we use 5 elements only, space for
other 5 elements is unutilized.
In other case if we need more than 10 elements, we need to change the array
definition.

Memory usage and allocation is very important in program. To manage memory


allocation and utilization ‘C’ supports dynamic memory allocation procedure.

Dynamic Memory Allocation

Dynamic memory allocation is a procedure in which the size of a data


structure/data variable is changed during the runtime.

‘C’ Provides some functions to support dynamic memory allocation. Following


library functions defined in <stdlib.h> header file to facilitate dynamic memory
allocation.

1. malloc()
2. calloc()
3. free()
4. realloc()

malloc(): malloc() or memory allocation function dynamically allocate a single large


block of memory with the specified size. It returns a pointer of type void which can
be cast into a pointer of any form.

Syntax: ptr= (cost-type *) malloc(byte-size)

Ex: ptr = (int *) malloc(100*sizeof(int));


If int occupies 2 bytes, this statement allocates 200 bytes of memory. ptr holds the
address of the first byte in the allocated memory.

calloc(): This function is used to dynamically allocate the specified number of blocks
of memory of the specified type. It initializes each block with a default value ‘0’.

Syntax: Ptr=(cast-type *) calloc(n,element-size)

Ex: ptr = (float *) calloc(25,sizeof(float));

This statement allocate contiguous space in memory for 25 elements each with the
size of float.

Department of Computer Science 15 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

realloc(): “realloc” or re allocation function is used to dynamically change the


memory allocation of a previously allocated memory. If the memory previously
allocated with help of malloc() or calloc() is insufficient, realloc() can be used to
dynamically re allocate memory.

Syntax: ptr = realloc(ptr, newsize)

Where ptr is reallocated with new size ‘ new size’.

free(): This function is used to dynamically de-allocate memory. The memory


allocated using functions malloc() and calloc() are not de-allocated on their own.
free() function is used to de-allocate memory. It helps to reduce wastage of memory.

Ex: free(ptr);

Files
Introduction to Files:
File:

File is a data structure, in which data can be stored permanently in required


format.

Redirecting I/O to a File:

Both read and write file operations can be easily performed under many
operating systems. If we want to write program results into a file, then command.

prog > data, will execute the program with the name ‘prog’ and writes the output
to the file called data.

We can redirect input from file also

Ex : reverse <file1

This command takes the value from file ‘file1’ and redirects to program called
‘reverse’.

We can redirect input and output to the program at the same time.
Ex : reverse < number > data

This command reads all the input for the program ‘reverse’ from file ‘number’
and write all the output to the file ‘data’.

Department of Computer Science 16 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

Using Files in ‘C’

Following are the main steps involved file processing

1. Opening File
2. Processing a File
3. Closing a File
Defining file Pointer :

A file is opened, accessed, closed through a file pointer. A file pointer is declared
using ‘FILE’, which is defined in <stdio.h>.

FILE *name of the file pointer;

Ex : FILE * fp;

The fopen () function :


Before doing any I/O operation on a file, the file must be opened. To open a file,
we must specify the name of the file. The function fopen() is used to open (or) create a
file. The general format of the fopen() function is

fopen (“filename”, “mode);


The function fopen () takes two arguments
i) filename ii) system type operation i.e. mode

Modes :

A file may be opened in one of the following modes

‘w’ mode This mode opens the file in write mode. Only file write is possible

‘r’ mode This mode opens the file in read mode. Only file read is possible

‘a’ mode This mode opens the file in append mode. In this mode data is
added
from the end of the existing data.

‘w+’ mode Write mode with read option

‘r+’ mode read mode with write option

‘a+’ mode append mode with read option

Department of Computer Science 17 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

If we add ‘b’ i.e ‘wb’, ‘rb’ etc., the file will be opened in binary mode for
corresponding system operation.

Ex : fp =fopen(“student.dat”, “w”);

This statement opens a file “student.dat” in write mode and return the file address
into file pointer ‘fp’.

The fopen() function opens the file, but if file is not existing the function creates a
file.

The fclose () Function :

When operations are completed on a file, it is good habit to close the file. When a
program terminates normally, the system automatically closes any open files. It is
generally better programming practice to close a file, as soon as we are done with it.
fclose() function is used to close an opened file.

The general format of fclose() is :

fclose (filepointer);

The argument to the fclose () is filepointer.

Ex : fclose (fp);

Closes the file defined by the file pointer ‘fp’.

Writing data into Files

Following Functions are used to write data into a File.

putc() :

The putc() function outputs one character to the file stream represented by the
specified file pointer. The syntax of putc() is :

char putc (char ch, FILE * stream);

Ex : putc (flag, fp);

This statement writes the character ‘flag’ to file pointed by ‘fp’

Department of Computer Science 18 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

The fprintf () Function :

The fprintf () is like printf ( ) except that this function writes the data to a
specified file. This function takes an additional parameter, which is the FILE pointer
that identifies the file to which data is to be written.

Ex : fprintf (fp, “programming in c is fun \n”);

This statement writes the specified string into a file identified by the file pointer
fp.

The fputs () Function :

fputs() function is used to write a string on to the file. The syntax of the fputs()
frunction is :

fputs(char *str, FILE *stream);

fputs() function writes the contents of the string pointed to by ‘str’ to the specified
stream. The null terminator is not written.
Ex: fputs(str, fp);

This statement writes the string ‘str’ in to the file pointed by the file pointer fp.

fwrite() : This function is used to write a record (or) structure to the file.

fwrite(&s, sizeof(structure),1,fp);

Structure ‘s’ will be stored into the file pointed by fp.

Ex: Following examples shows writing data into files.

1. open File // explain open file


2. wirite data //
3. close file // explain closing a file

# include “stdio.h”
main ()
{
FILE *fp;
int n;
char str[5];
printf(“\n Enter No.of Strings :”);
scanf(“%d”, &n);
fp =fopen(“Names.dat”, “w”);

Department of Computer Science 19 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

for (i=1; i<=n; i++)


{
scanf (“%s”, str);
fputs (str, fp);
}
fclose (fp);
}

Ex:- 2
main()
{
FILE *fp;
struct student
{
int sno;
char sname[20];
float marks;
};
int n;
struct student s;
fp=fopen(“ student.dat”,”w”);
printf(“Enter No. of students:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&s.sno);
gets(s.sname);
scanf(“%f”,&s.marks);
fwrite(&s,sizeof(struct student),1,fp);
}
fclose(fp);
}

This Program writes n records into a file “student.dat”;

Reading data from Files


Following Functions are used to read data from a File.

getc() :

The getc() function inputs one character from a specified file stream. The syntax
of getc() is :

char getc (FILE * stream);

Department of Computer Science 20 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

Ex : char flag ;
flag = get c (fp);

This statement inputs a character from the file defined by fp.

The fscanf () Function :

This function is used to read data from a file. The general format is

fscanf (File pointer, “control characters”, & variablenames);

Ex : fscanf (fp, “%d %f”, &a, &b);

This statement reads an integer and float value assigns them to variables ‘a’ and
‘b’ respectively from a file identified by ‘fp’.

The fgets () Function :


fgets() function is used to read a string from a file. The syntax of fgets() is as
shown below:
char *fgets(char *str, int num, FILE * stream);
The fgets() function reads upto ‘num’ characters from a file pointed by
‘stream’ and places them into the character array pointed to by ‘str’. Characters are
read until a new line or until the specified limit is reached.

Ex: fgets(str, 20, fp);

This statement reads a string of length 20 pointed by filepointer ‘fp’ to the


character array ‘str’.

fread() : This function is used to read a record / structure from the file.

fread(&s, sizeof(structure),1,fp);

Structure ‘s’ will be read from the file pointed by fp.

Ex: Following examples shows reading data from files.

1. open File // explain open file


2. read data //
3. close file // explain closing a file

Department of Computer Science 21 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

Ex:- 1
main()
{
FILE *fp;
char str[5];
fp = fopen (“names.dat”, “r”);
while (!feof(fp))
{
fgets(str, 5, fp);
prints(“\n%s”, str);
}
fclose (fp);
}

Ex:- 2
main()
{
FILE *fp;
struct student
{
int sno;
char sname[20];
float marks;
};
int n;
struct student s;
fp=fopen(“ student.dat”,”r”);
printf(“Enter No. of students:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
fread(&s,sizeof(struct student),1,fp);
printf(“\n sno : %d”,s.sno);
printf(“\n sname : %s,s.sname);
printf(“\nmarks:%f”,s.marks);
}
fclose(fp);
}

This Program reads n records from the file “student.dat”;

Department of Computer Science 22 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

Detecting the End of file


And end-file condition exists when the final piece of data has been read from a
file. Attempting to read after end of file might cause the program to terminate with an
error (or) it might cause the program to go into an infinite loop. feof() function is
defined in the standard I/O include file <stdio.h>

The feof () Function :


The feof() function checks the file position indicator to determine if the end of the
file associated with stream has been reached. A nonzero value is returned for the end of
the file, otherwise zero is returned.
Syntax : feof (filepointer);

Ex : while (! feof(fp))
{
.....
.....
}
The loop continues till end of the file.
Error Handling during File Operations

C language does not provide any direct support for error handling. However a few
methods and variables defined in error.h header file can be used to point out error
using the return statement in a function. In C language, a function returns -1 or
NULL value in case of any error and a global variable errno is set with the error
code. So the return value can be used to check error while program.

Errno:
Whenever a function call is made in C language, a variable named errno is
associated with it. It is a global variable, which can be used to identify which type of
error was encountered while function execution, based on its value. Below we have
the list of Error numbers and what do they mean.

errno Error Type


1 Operation not permitted
2 No such file or directory
3 No such process
4 Interrupted system call
5 I/O error
6 No such device or address
7 Argument list too long
8 Exec format error

Department of Computer Science 23 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

9 Bad file number


10 No child processes
11 Try again
12 Out of memory
13 Permission denied

C language uses the following functions to represent error messages associated with
errno:
 perror(): returns the string passed to it along with the textual represention of
the current errno value.
 strerror() is defined in string.h library. This method returns a pointer to the
string representation of the current errno value.

Other Operations on Files

stdin, stdout, stderr :


In ‘C’ when the program begins execution, the following three files will be
automatically opened.
1. Standard input, stdin
2. Standard output, stdout
3. Standard error, stderr

By default, the stdin, stdout, stderr refer to user’s console. This means that
whenever a program expects input from the standard input, it receives that input from
stdin. A program that writes to the standard output prints it data to stdout. Any error
messages that are generated by the library routines are sent to stderr.

ftell () : This function is used to locate the position of the file pointer. It returns a
long integer.

Ex : Long int L;
L=ftell (fp);

fseek() : This function is used to set the file pointer to the desired position.

fseek( fp, ibytes, pos);

rewind() : This function sets the file pointer to the initial position of the file.

Ex : rewind(fp).

Department of Computer Science 24 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

The exit() Function :

To explicitly terminate a program, the function exit () will be called.


exit (n) ; has the effect of terminating the current program. Any open files are
automatically closed by the system. The integer ‘n ‘ is called exit status.

Renaming and Removing Files :


rename () function is used to rename the existing file.
Ex : rename (“tempfile”, “database”);

This statement renames the file “tempfile” to “database”.


remove () function deletes the file specified by its argument.

Ex : remove (“tempfile”);

This statement deletes the file “tempfile”.


Ex: Following program explains copying contents of one file to another file

#include <stdio.h>
main ()
{
FILE *fp1, *fp2;
char flag;
fp1 = fopen (“Charadata1.data”, “r”);
fp2 = fopen (“Charadata2.data”, “w”);
while (! feof(fp))
{
flag = getc (fp1);
putc (flag, fp2);
}
fclose (fp1);
fclose (fp2);
getch();
}

In order to run above program the file chardata1.data should exists i.e. it should
be created. The while loop copies the contents of file chardata1.data to chardata2.data.

Header files used in ‘C’

A header file is a file with extension .h which contains C function declarations and
macro definitions and to be shared between several source files. There are two types
of header files: the files that the programmer writes and the files that come with
compiler.

Department of Computer Science 25 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

We request the use of a header file in our program by including it, with the C pre
processing directive #include.
Including a header file is equal to copying the content of the header file but we do
not do it because it will be very much error-prone and it is not a good idea to copy
the content of headerfile in the source files, specially if we have multiple source file
comprising our program.

A simple practice in C program is that we keep all the constants, macros, system
wide global variables, and function prototypes in header files and include that
header file wherever it is required.

List of header files in c language

No. Name Description


1 stdio.h Input/Output Functions
2 conio.h console input/output
3 assert.h Diagnostics Functions
4 ctype.h Character Handling Functions
5 cocale.h Localization Functions
6 math.h Mathematics Functions
7 setjmp.h Nonlocal Jump Functions
8 signal.h Signal Handling Functions
9 stdarg.h Variable Argument List Functions
10 stdlib.h General Utility Functions
11 string.h String Functions
12 time.h Date and Time Functions
13 complex.h A set of function for manipulating complex numbers
14 stdalign.h For querying and specifying the alignment of objects
15 errno.h For testing error codes
16 locale.h Defines localization functions
17 stdatomic.h For atomic operations on data shared between threads
18 stdnoreturn.h For specifying non-returning functions
19 uchar.h Types and functions for manipulating Unicode characters
20 fenv.h A set of functions for controlling the floating-point
environment
21 wchar.h Defines wide string handling functions
22 tgmath.h Type-generic mathematical functions
23 stdarg.h Accessing a varying number of arguments passed to functions
24 stdbool.h Defines a boolean data type

Department of Computer Science 26 A.S.N. Degree College, Tenali


Programming using C UNIT-V I SEMESTER B.C.A

Department of Computer Science 27 A.S.N. Degree College, Tenali

You might also like