CP Unit 6
CP Unit 6
CP Unit 6
com
COMPUTER PROGRAMMING UNIT-6
UNIT-6
POINTER
A pointer provides a way of accessing a variable without referring to the variable
directly. A pointer variable is a variable that holds the memory address of another
variable. The pointer does not hold a value. A pointer points to that variable by holding a
copy of its address. It has two parts
1) the pointer itself holds the address
2) the address points to a value
Uses of pointers:
1) Call by Address
2) Return more than one value from a function
3) Pass array and string more conveniently from one function to another
4) Manipulate arrays more easily
5) Create complex data structures
6) Communicate information about memory
7) Fast compile
Declaring Pointer: The pointer operator a variable in C is ‘*’ called “value at address”
operator. It returns the value stored at a particular memory the value at address operator is
also called “indirection” operator a pointer variable is declared by preceding its name
with an asterisk(*) .
Syntax: datatype *pointer_variable;
Where datatype is the type of data that the pointer is allowed to hold and pointer_variable
is the name of pointer variable.
Example:
int *ptr;
char *ptr;
float *ptr;
Sample program:
main()
{
int *p;
float *q;
double *r;
printf(“Size of the integer pointer %d”,sizeof(p));
printf(“size of the float pointer %d”,sizeof(q));
printf(“size of double pointer %d”,sizeof(r));
}
Initializing Pointers:
A pointer must be initialized with a specified address operator to its use. For example to
store the address of I in p, the unary & operator is to be used.
P=&I;
Sample program:
main()
{
int num=5;
int *ptr=#
printf(“the address num is %p”,&num);
printf(“the address num is %p”,ptr);
}
1) Assignment: pointers with the assignment operators can be used if the following
conditions are
1) lefthand side operand is a pointer is a pointer and right hand operand is a null
pointer constant.
2) Incompatible type of pointer assignment
3) Both the operands are pointers to compatibles.
Sample program:
main()
{
int i;
int *ip;
void *vp;
ip=&i;
vp=ip;
ip=vp;
if(ip!=&i)
printf(“Compiler error”);
else
printf(“no compiler error”);
}
3) Subtraction: the operator ‘-‘ performs the subtraction operation between the pointer
and number. For example p is a pointer. Pointer p subtract value 5 mean (p-5).
Example:
main()
{
double a[2],*p,*q;
p=a;
p=p-1;
printf(“%d”,(int)q-(int)p);
}
4) Comparing pointers: C allows pointer to be compared with each other. If two pointer
compare equal to each other.
main()
{
int a,*p,*q;
p=&a;
q=&a;
if(*p==*q)
printf(“both are equal”);
}
5) Assign the value 0 to the pointer and compare 0 with pointer: P declare as a
pointer naturally it stores the address of another variable. Suppose 0 assigned to pointer,
like p=0; and also pointer variable p compared with 0.
For example,
main()
{
int *p;
p=0;
if(p==0)
printf(“P contains zero”);
else
printf(“p contains a non-zero value”);
}
Pointers to pointers: Pointers to pointers concept supports the pointer of pointer, means
pointer stores address of another variable. Pointer of pointer stores address of another
pointer.
int a=5;
int *p;
int **q;
p=&a;
q=*p;
Pointers to functions: Pointers are pointer i.e., variable which point to the address of a
function. A running program is allocated a certain space in the main memory.
The names of the functions add and sub is pointers to those functions. These can be
assigned to pointer variables.
fpointer=add;
fpointer=sub;
Calling of a function using a function pointer: in c there are two ways of calling a
function using a function pointer. Use the name of the function pointer instead of the
name of the function pointer instead of the name of the function or explicitly deference it.
Result=fpointer(4,5);
Result2=fpointer(6,2);
Example:
int (*fpointer)(int,int);
int add(int,int);
int sub(int,int);
main()
{
fpointer=add;
printf(“%d”,fpointer(4,5));
fpointer=sub;
printf(“%d”,fpointer(6,2));
}
int add(int a,int b)
{
return (a+b);
}
int sub(int a,int b)
{
return (a-b);
}
Pointers to an Array: we can declare a pointer to a simple integer value and make it
point to the array asa is done normally.
int v[5]={1004,2201,3000,432,500};
int *p=v;
printf(“%d”,*p);
This piece of code displays the number, which the pointer p points to, that is the first
number in the array namely 1004.
P++ this instruction increases the pointer so that it points to the next element of the array.
printf(%d”,*p); this statement prints value 2201.
With exit(), status is provided for the calling process as the exit status of the process.
STATUS INDICATES
EXIT_SUCCESS Normal program terminals
EXIT_FAILURE Abnormal program termination
#include<stdio.h>
#include <malloc.h>
int main(){
void *ptr;
printf("%d",*ptr);
return 0;
}
Output: Compiler error
3. Generic pointer can hold any type of pointers like char pointer, struct pointer, array of
pointer etc without any typecasting.
Example:
#include<stdio.h>
int main(){
char c='A';
int i=4;
void *p;
char *q=&c;
int *r=&i;
p=q;
printf("%c",*(char *)p);
p=r;
printf("%d",*(int *)p);
return 0;
}
Output: A4
4. Any type of pointer can hold generic pointer without any typecasting.
5. Generic pointers are used when we want to return such pointer which is applicable to
all types of pointers. For example return type of malloc function is generic pointer
because it can dynamically allocate the memory space to stores integer, float, structure
etc. hence we type cast its return type to appropriate pointer type.
Examples:
1. char *c;
c= (char *)malloc(sizeof(char));
2. double *d;
d= (double *)malloc(sizeof(double));
3. Struct student{
char *name;
int roll;
};
Struct student *stu;
Stu=(struct student *)malloc(sizeof(struct student));
If any pointer is pointing the memory address of any variable but after some variable has
deleted from that memory location while pointer is still pointing such memory location.
Such pointer is known as dangling pointer and this problem is known as dangling pointer
problem.
Initially:
Later:
For example:
(q)What will be output of following c program?
#include<stdio.h>
int *call();
void main(){
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
}
int * call(){
int x=25;
++x;
return &x;
}
Output: Garbage value
Note: In some compiler you may get warning message returning address of local
variable or temporary
Explanation: variable x is local variable. Its scope and lifetime is within the function call
hence after returning address of x variable x became dead and pointer is still pointing ptr
is still pointing to that location.
#include<stdio.h>
int *call();
void main(){
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
}
int * call(){
static int x=25;
++x;
return &x;
}
Output: 26
The string literal is used as the initializer for the array amessage. amessage is here an array
of 16 characters, which we may later overwrite with other characters if we wish. The
string literal merely sets the initial contents of the array. In the definition
char *pmessage = "now is the time";
on the other hand, the string literal is used to create a little block of characters somewhere
in memory which the pointer pmessage is initialized to point to. We may reassign pmessage
to point somewhere else, but as long as it points to the string literal, we can't modify the
characters it points to.
The first function is strcpy(s,t), which copies the string t to the string s. It would be
nice just to say s=t but this copies the pointer, not the characters.
This is a restatement of what we said above, and a reminder of why we'll need a function,
strcpy, to copy whole strings.
Once again, these code fragments are being written in a rather compressed way. To make
it easier to see what's going on, here are alternate versions of strcpy, which don't bury the
assignment in the loop test. First we'll use array notation:
void strcpy(char s[], char t[])
{
int i;
for(i = 0; t[i] != '\0'; i++)
s[i] = t[i];
s[i] = '\0';
}
Note that we have to manually append the '\0' to s after the loop. Note that in doing so we
depend upon i retaining its final value after the loop, but this is guaranteed in C, as we
learned in Chapter 3.
Here is a similar function, using pointer notation:
void strcpy(char *s, char *t)
{
while(*t != '\0')
*s++ = *t++;
*s = '\0';
}
Again, we have to manually append the '\0'. Yet another option might be to use a do/while
loop.
ptr=(int*)malloc(a*sizeof(int));
ptr=a;
printf("%d",ptr);
free(ptr);
getch();
}
calloc() function
The calloc function is used to allocate storage to a variable while the program is
running. This library function is invoked by writing calloc(num,size).This function takes
two arguments that specify the number of elements to be reserved, and the size of each
element in bytes and it allocates memory block equivalent to num * size . The important
difference between malloc and calloc function is that calloc initializes all bytes in the
allocation block to zero and the allocated memory may/may not be contiguous.
For example, an int array of 10 elements can be allocated as follows.
int * array = (int *) calloc (10, sizeof (int));
Note that this function can also malloc, written as follows.
int * array = (int *) malloc (sizeof (int) * 10);
ptr = malloc(10 * sizeof(int)); is just like this:
ptr = calloc(10, sizeof(int));
The following example illustrates the use of
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *ptr,a[6]={1,2,3,4,5,6};
int i;
ptr=(int*)calloc(a[6]*sizeof(int),2);
for(i=0;i<7;i++)
{
printf("\n %d",*ptr+a[i]);
}
free(ptr);
getch();
}
realloc()
With the function realloc, you can change the size of the allocated area once. Has the
following form.
void * realloc (void * ptr, size_t size);
The first argument specifies the address of an area that is currently allocated to the size in
bytes of the modified second argument. Change the size, the return value is returned in
re-allocated address space. Otherwise it returns NULL.
The address of the source address changed, but the same could possibly be different, even
if the different areas of the old style, because it is automatically released in the function
realloc, for the older areas it is not necessary to call the free function.
#include<alloc.h>
#include<string.h>
main()
{
char *str;
clrscr();
str=(char*)malloc(6);
str=("india");
printf("str=%s",str);
str=(char*)realloc(str,10);
strcpy(str,"hindustan");
printf("\nnow str=%s",str);
free(str);
getch();
}
free() function
Next, how to release the reserved area, which will use the function free. Has also been
declared in stdlib.h, which has the following form.
void free (void * ptr);
The argument specifies the address of a dynamically allocated area. You can then free up
the space. Specify an address outside the area should not be dynamically allocated. Also, if
you specify a NULL, the free function is guaranteed to do nothing at all
So, an example program that uses functions malloc and free functions in practice.
# include<stdlib.h>
# include<conio.h>
int main (void)
{
int * p;
p = (int *) malloc (sizeof (int)); /* partitioning of type int */
if (p == NULL) * / failed to reserve area * /
{
printf ("Failed to allocate space for% d bytes", sizeof (int));
return 1;
}
* P = 150;
printf ("% d \ n", * p);
free (p); * / free area * /
return 0;
}
#include <stdio.h>
Note that *argv[0] is the name of the program invoked, which means that *argv[1] is a
pointer to the first argument supplied, and *argv[n] is the last argument. If no arguments
are supplied, argc will be one. Thus for n arguments, argc will be equal to n + 1. The
program is called by the command line,
myprog argument1
Example : commandline.c
#include<stdio.h>
main(int argc,int *argv[])
{
int i;
printf("No of arguments %d",argc);
for(i=0;i<argc;i++)
{
printf("\n %s",argv[i]);
}
}
C:\CSE>filename arg1 arg2 …….. argn
C:\CSE>commandline hello how are u
No of arguments 5
commandline
hello
how
are
u
DERIVED DATATYPES:
C provides facilities to construct user defined datatypes. A user defined datatypes
may also be called a derived datatype. Some of the datatypes are…
1. structures
2. unions
3. typedef
4. arrays
5. enumerators…etc.,
STRUCTURE
Def. of structure:
Structure is the user defined datatype that can hold a heterogeneous datatypes.
Structures are constructing with “struct” keyword and end with semicolon…
In the above syntax structurename is the name of the structure. The structure variables are
the list of the variable names separated by comas. Variables declared with in the braces
called members or variables.
Example:
struct country
{
char name[30];
int population;
char language[15];
} India,japan,England;
In the above example country is the structure name and structure members are
name, population, language and structure variable are India, Japan and England.
Initialisation of structure:
This consists of assigning some constants to the constants to the members of the
structure. Default values for integer and float datatype members are zero. For char
member default value ‘\0’ (null).
Syntax:
struct struct name
{
datatype member1;
.
.
.
datatype member n;
}<structvariable>={constant1,constant2…}
Example:
#include<stdio.h>
struct item
{
int count;
float avgweight;
int date,month,year;
} batch={2000,25.3,07,11,2010};
main()
{
printf(“\n count=%d”,batch.count);
printf(“\n averageweight=%f”,batch.avgweight);
printf(“\nmfg-date=%d%d%d”,batch.date,batch.month,batch.year);
}
Nested structures:
A structure can be placed with in another structure. In other
words structures can contain other structures as members. A structure with in a structure
means nested structures.
A
B
C
Example:
#include<stdio.h>
struct b
{
int x;
struct b
{
int y;
struct c
{
int z
}c1;
}b1;
}a1;
main()
{
a1.x=10;
a1.b1.y=20;
a1.b1.c1.z=30;
Arrays of structures:
This means that the structure variable would be an array of objects. Each of which
contains the number elements declared within the structure construct.
Syntax:
struct <structname>
{
<datatype member1>;
<datatype member2>;
.
.
.
<datatype member n>;
}<structure variable[index];
(or)
struct <structname><structurevariable>[index];
Example:
#include<stdio.h>
struct Prasad
{
int a;
float b;char c;
};
main()
{
struct Prasad p[3];
int i;
clrscr();
printf(“enter details\n”);
for(i=0;i<3;i++)
scanf(“%d%f%c”,&p[i].a,&p[i].b,&p[i].c);
printf(“entered details are \n”);
for(i=0;i<3;i++)
printf(“%d%f%c”,p[i].a,p[i].b,p[i].c);
getch();
}
Example:
struct student
{
char name[20];
int a[10];
float b[20];
}s;
main()
{
clrscr();
printf(“the size of the structure is %d”,sizeof(s));
getch();
}
Syntax:
struct <structname>
{
<datatype member1>;
<datatype member2>;
.
.
<datatype membern>;
}*ptr;
Or
struct <structname> *ptr;
The pointer *ptr can be assigned to any other pointer of the same type and can be used to
access the members of its structure using pointer ,access the structure members in two
ways…
One is…
(*ptr).member1;
The bracket is needed to avoid confusion about ‘*’ and ‘.’ Operators.
Second is…
ptrmember1;
This is less confusing and better way to access a member in a structure through
its pointer. The operator, an arrow made out of a minus sign and a greater than symbol.
Example:
#include<stdio.h>
#include<conio.h>
struct abc
{
int a;
float b;
}*p;
main()
{
printf(“initialization for members/n”);
pa=10;
pb=20.12;
printf(“a=%d,b=%f”,pa,pb);
printf(“read the values in”);
scanf(“%d%f”,&pa,pb);
printf(“\n a=%d,b=%f”,pa,pb);
}
Example:
#include<stdio.h>
struct A
{
char ch;
int i;
float f;
};
void show(struct A);
main()
{
struct A x;
printf(“in entre ch,i and f”);
scanf(“%c%d%f”,&x.ch,&x.i,&x.f);
show(x);
}
void show(A b)
{
printf(“%c%d%f”,b.ch,b.i,b.f);
}
typedef:
The typedef keyword allows the programmer to create a new datatype
name for an existing datatype. No new datatype is produced but an alternative name is
given to a known datatype
Syntax:
typedef <existing datatype><new datatype,…>;
typedef statement does not occupy storage, it simply defines a new type.
typedef int id;
typedef float wt;
typedef char lw;
id is the new datatype name given to datatype int, while wt is the new datatype name
given to the datatype float,a nd lw is the new datatype name given to datatype char…
id x,y,z;
wt p,m;
lw a,b;
x,y and z are variable names that are declared to hold int datatype.
Example:
main()
{
typedef int Prasad;
Prasad a,b,c;
a=10;b=20;
c=a+b;
printf(“%d”,c);
}
In structures
#include<stdio.h>
typedef struct point
{
int x;
int y;
}data;
main()
{
data lt,rt;
printf(“enter x and y coordinates of left and right”);
scanf(“%d%d%d%d”,<.x,<.y,&rt.x,&rt.y);
printf(“left:x=%d,y=%d.right:x=%d,y=%d”,lt.x,lt.y,rt.x,rt.y);
getch();
}
Union:
Union is the user defined datatype that can hold heterogeneous datatypes. Unions
are construct with “union” keyword. Unions are end with semicolon.
Syntax:
union unionname
{
Member1;
Member2;
.
.
.
Member n;
}variable1,variable2…..variable n;
Union also has a union name,members and variable names. The union variables
are declared with following syntax.
Union unionname variable1,variable2….variable n;
Example:
union mixed
{
char ch[10];
float marks[10];
int no[10];
}all;
Union members share the same storage
1 10 20 30 40
-------char-------------
10bytes
--------------int 20 bytes-----------------------
-----------------------------float 40 bytes--------------------------------------------------------------
Example:
#include<stdio.h>
#include<conio.h>
union exp
{
int i;
char c;
}var;
main()
{
var.i=65;
var.c=var.i;
printf(“\n var.i=%d”,var.i);
printf(“\n var.c=%c”,var.c);
getch();
}
Enumeration types:
Enumeration datatypes are data items whose values may be any number of a
symbolically declared set of values the symbolically declared members are integer
constants. The keyword enum is used to declare an enumeration type. Simply
“enumerators are named integers”
The general form of the enumerator is
enum <enumerator name>
{
Member1;
Member2;
.
.
.
Member n;
}var1,var2,…var n;
The enum enumerator name specifies the userdefined type the member are
integer constants, by default ,the first member, that is member1 is given the value0.
Example:
#include<stdio.h>
enum days
{
Mon,tue,wed,thur,fri,sat,sun
};
main()
{
enum days start,end;
start=tue;
end=sat;
printf(“start=%d,end=%d”,start,end);
start=64;
printf(“\n start now is equal to %d”,start);
getch();
}
Example:
#include<stdio.h>
enum rank
{
Ramu,ramesh,Prasad=10,vinaya,rani
}v;
main()
{
v=ramesh;
printf(“ramesh rank is %d\n”,r);
v=Prasad;
printf(“prasad rank is %d\n”,r);
v=rani;
printf(“\n rani rank is %d”,r);
getch();
}
Defines a datatype, struct node. A structured of type struct node has two members-
integer member data and pointer member nextptr. Member nextptr points to a structure of
type struct node-a structure of the same type as one being declared here, hence the term
“self referential structure” member nextptr is refered to as link i.e nextptr can be used to
“tie” a structure of type struct node to another structure of the sametype.
Example:
#include<stdio.h>
main()
{
struct stinfo
{
char name[20];
int age;
char city[20];
struct stinfo *next;
};
struct stinfo s1={“rani”,25,”kkd”};
struct stinfo s2={“raju”,27,”rjy”};
struct stinfo s3={“sita”,29,”amp”};
s1.next=&s2;
s2.next=&s3;
s3.next=NULL;
printf(“student name=%s,age=%d,city=%s”,s1.name,s2.age,s3.city);
printf(“student1 stored at %x \n”,s1.next);
printf(“student2 name=%s,age=%d,city=%s”,s2.name,s2.age,s2.city);
printf(“student2 stored at %x\n”,s2.next);
printf(“student3 name=%s,age=%d,city=%s”,s3.name,s3.age,s3.city);
printf(“student3 stored at %x\n”,s3.next);
}
The next three statement in the program
s1.next=&s2;
s2.next=&s3;
s3.next=NULL;
Setup the linked list , with the next member of s1 pointing to s2 and the next member
of s2 pointing to s3 and next member of s3 pointing to NULL.
Bitfields:
There are two ways to manipulate bits in c. one of the ways consists of using
bitwise operators . the other way consists of using bit fields in which the definition and
the access method are based on structure.
struct bitfield_tag
{
unsigned int member1:bit_width1;
unsigned int member2:bit_width2;
.
.
.
unsigned int member n:bit_width n;
};
Each bitfield for example ‘unsigned int member1:bit_width1’ is an integer that has a
specified bit width. By this technique the exact number of bits required by the bit field is
specified.
Structure variable name status_byte containing four unsigned bitfields. The value
assigned to a field must not be greater than its maximum storage value.
The assignment of the structure member is
Chk_sum=6;
Sets the bits in the field chk_sum on 110.
Structure Union
1. structure is the user defined 1. union is the user defined datatype.
datatype . 2. union are construct with union
2. structure are constructed with keyword.
struct keyword.
3. members share the same memory.
3. structures members are stored in
individual storage.
4. occupied less memory.
4. occupied more memory.
5. member accessing is difficult. 5. member accessing is easy.
Array Pointer
1. Array allocates space 1. It is explicitly assigned to point
automatically. to an allocated space.
2. It cannot be resized. 2. It can be resized using realloc().
3. It cannot be reassigned. 3. It can be reassigned.
4. sizeof(arrayname) gives the 4. sizeof(p) returns the number of
number of bytes occupied by bytes used to store the point
array. variable.
Array Structure
1. Group of homogeneous elements. 1. Group of heterogeneous
2. Array is derived datatype. elements.
3. An array behavior like a built in 2. Structure is a user defined
datatype. datatype.
4. Elements differ with index. 3. Structure behaves like a built in
5. sizeof(arrayname) gives the different datatypes.
number of bytes occupied by the 4. members differ with datatype
array. and member name.
5. sizeof(structurevariable) returns
the number of bytes used to
store the structure variable.
File management in C
FILE:
A file is an external collection of related data treated as a unit. The primary purpose of a
file is to keep a record of data. files are stored in auxiliary or secondary storage devices .
Buffer is a temporary storage area that holds data while they are being transferred to or
from memory.
Streams
A stream can be associated with a physical device, such as a terminal, or with a file
stored in auxiliary memory.
Your program must open a file before it can access it. This is done using the fopen
function, which returns the required file pointer. If the file cannot be opened for any
reason then the value NULL will be returned. You will usually use fopen as follows
if ((output_file = fopen("output_file", "w")) == NULL)
fprintf(stderr, "Cannot open %s\n", "output_file");
fopen takes two arguments, both are strings, the first is the name of the file to be opened,
the second is an access character, which is usually one of r, a or w etc. Files may be
opened in a number of modes, as shown in the following table.
File Modes
r Open a text file for reading.
w Create a text file for writing. If the file exists, it is overwritten.
a Open a text file in append mode. Text is added to the end of the file.
rb Open a binary file for reading.
wb Create a binary file for writing. If the file exists, it is overwritten.
Open
ab a binary file in append mode. Data is added to the end of the file.
r+ Open a text file for reading and writing.
w+ Create a text file for reading and writing. If the file exists, it is overwritten.
a+ Open a text file for reading and writing at the end.
r+b or rb+ Open binary file for reading and writing.
w+b orwb+ Create a binary file for reading and writing. If the file exists, it is
overwritten.
a+b or ab+ Open a text file for reading and writing at the end.
The update modes are used with fseek, fsetpos and rewind functions. The fopen function
returns a file pointer, or NULL if an error occurs.
The following example opens a file, tarun.txt in read-only mode. It is good programming
practice to test the file exists.
File operation functions in C, Defining and opening a file, Closing a file, The getw and
putw functions, The fprintf & fscanf functions
C supports a number of functions that have the ability to perform basic file operations,
which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
Real life situations involve large volume of data and in such cases, the console
oriented I/O operations create two major problems
It becomes burden and time consuming to handle large volumes of data through
terminals.
The entire data is lost when either the program is terminated or computer is turned
off.
File operation functions in C:
Function Name Operation
fopen() Creates a new file for use
Opens a new existing file for use
fclose Closes a file which has been opened for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads a integer from a file
putw() Writes an integer to the file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the begining of the file
Defining and opening a file:
If we want to store data in a file into the secondary memory, we must specify certain
things about the file to the operating system. They include the fielname, data structure,
purpose.
The general format of the function used for opening a file is
FILE *fp;
fp=fopen(“filename”,”mode”);
The first statement declares the variable fp as a pointer to the data type FILE. As stated
earlier, File is a structure that is defined in the I/O Library. The second statement opens
the file named filename and assigns an identifier to the FILE type pointer fp. This
pointer, which contains all the information about the file, is subsequently used as a
communication link between the system and the program. The second statement also
specifies the purpose of opening the file. The mode does this job.
In these statements the p1 and p2 are created and assigned to open the files data and
results respectively the file data is opened for reading and result is opened for writing. In
case the results file already exists, its contents are deleted and the files are opened as a
new file. If data file does not exist error will occur.
Closing a file:
The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);
A file must be closed as soon as all operations on it have been completed. This would
close the file associated with the file pointer.
Observe the following program.
….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….
…
fclose(p1);
fclose(p2)
The above program opens two files and closes them after all operations on them are
completed, once a file is closed its file pointer can be reversed on other file.
The getc and putc functions are analogous to getchar and putchar functions and handle
one character at a time. The putc function writes the character contained in character
variable c to the file associated with the pointer fp1. ex putc(c,fp1); similarly getc
function is used to read a character from a file that has been open in read mode.
c=getc(fp2).
The program shown below displays use of a file operations. The data enter through the
keyboard and the program writes it. Character by character, to the file input. The end of
the data is indicated by entering an EOF character, which is control-z. the file input is
closed at this signal.
{
if(number%2==0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“nnContents of the odd filenn”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“nnContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}
The fprintf & fscanf functions:
The fprintf and fscanf functions are identical to printf and scanf functions except that they
work on files. The first argument of these functions is a file pointer which specifies the
file to be used. The general form of fprintf is
fprintf(fp,”control string”, list);
Where fp id 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:
#include <stdio.h>
int main()
{
FILE *fp;
file = fopen("file.txt","w");
fprintf(fp,"%s","This is just an example :)");
fclose(fp);
return 0;
}
Variables
Variables defined in the stdio.h header include:
Name Notes
stdin a pointer to a FILE which refers to the standard input stream, usually a keyboard.
a pointer to a FILE which refers to the standard output stream, usually a display
stdout
terminal.
a pointer to a FILE which refers to the standard error stream, often a display
stderr
terminal.
fflush
Defined in header <stdio.h>
int fflush( FILE *stream );
Causes the output file stream to be synchronized with the actual contents of the file. If the
given stream is of the input type, then the behavior of the function is undefined.
Parameters
Return value
Returns zero on success. Otherwise EOF is returned and the error indicator of the file
stream is set.
Text Files in C
A file is for storing permanent data. C provides file operations in stdio.h. A file is
viewed as a stream of characters. Files must be opened before being accessed, and
characters can be read one at a time, in order, from the file.
There is a current position in the file's character stream. The current position starts
out at the first character in the file, and moves one character over as a result of a character
read (or write) to the file; to read the 10th character you need to first read the first 9
characters (or you need to explicitly move the current position in the file to the 10th
character).
There are special hidden chars (just like there are in the stdin input stream), '\n', '\t',
etc. In a file there is another special hidden char, EOF, marking the end of the file.