You are on page 1of 72

EST102

PROGRAMMING IN C

MODULE V
SYLLABUS
Pointers and Files
Basics of Pointer: declaring pointers, accessing
data through pointers, NULL pointer, array
access using pointers, pass by reference effect
File Operations: open, close, read, write,
append
Sequential access and random access to files:
In built file handling functions
(rewind() ,fseek(), ftell(), feof(), fread(),
fwrite())
Important!!
➔ Pointer - Definition, Example, Declaration and
Initialization, Advantages and Disadvantages
➔ Symbols used in Pointers
➔ Pointer to a Pointer - Questions like Output
prediction
➔ NULL Pointer
➔ C Programs using Pointers
➔ Need for File Handling in C
➔ File Operations in C
➔ Significance of File Pointer
➔ File Opening Modes in C
➔ Sequential Access VS Random Access
➔ C programs using Files
Basics of Pointer
Pointer
• The pointer in C language is a variable.
• It is also known as locator or indicator that
points to an address of a value.
• A pointer is a derived data type that refers to
another data variable by storing the variable’s
memory address rather than data.
Consider the declaration,
int i = 5;
This declaration tells the C compiler to:
a) Reserve space in memory to hold the integer
value.
b) Associate the name i with this memory
location.
c) Store the value 5 at this location.
We see that the computer has selected
memory location 1000 as the place to
i store the value 5. The important point is,
1000 5 i’s address in memory is a number.
Symbols used in Pointer

Symbol Name Description

& Determine
Address
(Ampersan the address
Operator
d sign) of a variable
* Access the
Indirection
(Asterisk value of an
Operator
sign) address
Declaring and Initializing
Pointers
• The process of assigning the address of a
variable to a pointer variable is known as
initialization.
• The only requirement here is that variable
quantity must be declared before the
initialization takes place.
• General syntax for declaring and initializing
a pointer variable is,
data_type *pointer_variable;
pointer_variable=&variable_name;
Asterisk(*) can be located immediately
before the pointer variable, or between the
data type and pointer variable, or
immediately after the data type.
For example,
int a;
a=10;
int *ptr; //declaration
ptr = &a; //initialization
We can also combine the initialization with
the declaration.
int a=10;
int *ptr = &a;
Question No. 1
Write a C program to add two numbers using
pointers.
Program
#include<stdio.h>
int main()
{
int a,b,*p,*q,sum;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
p=&a;
q=&b;
sum=*p+*q;
printf("Sum=%d\n",sum);
return 0;
}
Output
Enter two numbers
10
6
Sum=16
Question No. 2
Write a C program to swap two numbers using
pointers.
Program
#include<stdio.h>
int main()
{
int a,b,*m,*n,temp;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
m=&a;
n=&b;
printf("Before swapping:\na=%d\nb=%d\n",a,b);
temp=*m;
*m=*n;
*n=temp;
printf("After swapping:\na=%d\nb=%d\n",a,b);
return 0;
}
Output
Enter two numbers
30
20
Before swapping:
a=30
b=20
After swapping:
a=20
b=30
Pointer to a Pointer
(Chain of Pointers)
• It is possible to make pointer to point to another
pointer.
• Pointer is a variable that contains address of
another variable. Now this variable itself might
be another pointer. Thus, we now have a pointer
that contains another pointer’s address.
• The representation is called multiple indirection.
Question No. 3
What will be the output of the following C program?
#include<stdio.h>
int main()
{
int a,*p,**q;
a=120;
p=&a;
q=&p;
printf("Value of a=%d\n",a);
printf("Value available at *p=%d\n",*p);
printf("Value available at **q=%d\n",**q);
return 0;
}
a = 120
p = &a
=> p = address of a
=> p = 2500
q = &p
=> q = address of p
=> q = 5000
Value of a = 120
Value available at *p = *(2500) = 120
Value available at **q = *(*(5000)) = *(2500) = 120
Output
Value of a=120
Value available at *p=120
Value available at **q=120
Question No. 4
Write a C program to find sum of n numbers using
pointers.
Program
#include<stdio.h>
int main()
{
int a[10],i,n,sum,*ptr;
printf("Enter the limit\n");
scanf("%d",&n);
printf("Enter the elements\n");
sum=0;
ptr=a; //ptr=&a[0];
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+*ptr;
ptr++;
}
printf("Sum=%d\n",sum);
return 0;
}
Output
Enter the limit
3
Enter the elements
10
20
30
Sum=60
NULL Pointer
• A null pointer in C is a pointer that is assigned
to zero or NULL where a variable that has no
valid address.
• The null pointer usually does not point to
anything.
• In C programming language NULL is a macro
constant that is defined in a few of the header
files like stdio.h, alloc.h, mem.h, stddef.h,
stdlib.h.
• Also, note that NULL should be used only
when we are dealing with pointers only.
• Syntax for declaring NULL pointer is as
follows:
int *pointer_var;
pointer_var=NULL;
or
int *pointer_var = NULL;
or
int *pointer_var;
pointer_var=0;
or
int *pointer_var = 0;
Advantages of using Pointer
1) Less time in program execution
2) Working on the original variable
3) With the help of pointers, we can create
data structures (linked-list, stack, queue).
4) Returning more than one values from
functions
5) Searching and sorting large data very
easily
6) Dynamically memory allocation
Disadvantages of using Pointer
1) Sometimes by creating pointers, such
errors come in the program, which is very
difficult to diagnose.
2) Sometimes pointer leaks in memory are
also created.
3) If extra memory is not found then a
program crash can also occur.
Files
Files
• A file represents a sequence of bytes,
regardless of it being a text file or a binary
file.
• C programming language provides access on
high level functions as well as low level (OS
level) calls to handle file on your storage
devices.
Need for File Handling in C
• Reusability helps to retain the data collected
after the software is run.
• Huge storage capacity you don’t need to
think about the issue of mass storage using
data.
• Save time Unique applications need a lot of
user feedback. You can quickly open some
aspect of the code using special commands.
• Portability You can quickly move file
material from one operating device to
another without thinking about data loss.
File Operations
1) Creation of a new file
(fopen with attributes as “a” or “a+” or “w” or “w++”)
2) Opening an existing file
(fopen)
3) Reading from file
(fscanf or fgets)
4) Writing to a file
(fprintf or fputs)
5) Moving to a specific location in a file
(fseek, rewind)
6) Closing a file
(fclose)
Declaring a file pointer
• Before opening a file, we have to declare a
pointer to a structure of type FILE called a
file pointer.
• The FILE type is a structure that contains
information needed for reading and writing a
file.
• The information generally includes the
operating system’s name for the file, the
current character position in the file, whether
the file is being read or written and so on.
• This structure declares within the header file
stdio.h.
• The declaration of the file pointer made as
follows,
FILE *fp;
fp is the name of the file pointer which is
declared as a pointer to a structure of type
FILE.
Opening a file
for creation and edit
• Once the file pointer has been declared, the
next step is to open an appropriate file to
perform any operation.
• This is done using the function fopen(),
specified in the header file stdio.h.
• To open a file, the syntax is:
fp=fopen("filename","mode");
• The fopen() function takes two parameters,
both of which are strings.
• The parameter filename is the name of the disk file
to open.
• The file name generally consists of two parts: a
primary name and an optional extension, which
separates from the primary name by a period (.).
• The second parameter mode specifies how the file is
to be opened, ie, for reading, writing both reading
and writing, appending at the end of the file etc.
• If the call to the fopen() function is successful, the
function returns a pointer of type FILE.
• This pointer must use in subsequent operations on
the file, such as reading from or writing.
• If the file cannot open for some reason, fopen()
returns a NULL pointer. ·
File Opening Modes in C
Closing a file
• When all operations on a file have complete, it
must be closed.
• As a result, the file disassociates from the file
pointer.
• Although when the program exits, all open files are
closed automatically, however explicitly closing a
file has the following advantages,
– Prevents accidental misuse of the file.
– As there is a limit to the number of files that can
keep open simultaneously, closing a file may
help open another file.
– The closed file can again open in a different
mode as per requirement.
• In C, a file is closed by the function fclose().
• It has the following syntax,
fclose(fp);
• This function accepts a file pointer as an
argument and returns a value of type int.
• If the fclose() function closes the file
successfully, then it returns an integer value 0.
Otherwise, it returns EOF.
feof()
feof() function is a file handling function in C
programming language which is used to find
the end of a file.
In a C program, we use feof() function as,
feof(fp);
where,
fp – file pointer
fwrite()
The fwrite() function is used to write records (sequence of bytes) to
the file.
A record may be an array or a structure.
Syntax of fwrite() function
fwrite( ptr, int size, int n, FILE *fp );
The fwrite() function takes four arguments.
ptr : ptr is the reference of an array or a structure stored in
memory.
size : size is the total number of bytes to be written.
n : n is number of times a record will be written.
FILE* : FILE* is a file where the records will be written in binary
mode.
fp : file pointer
fread()
The fread() function is used to read bytes from the record.
A record may be an array or a structure.
Syntax of fread() function
fread( ptr, int size, int n, FILE *fp );
The fread() function takes four arguments.
ptr : ptr is the reference of an array or a structure where
data will be stored after reading.
size : size is the total number of bytes to be read from file.
n : n is number of times a record will be read.
FILE* : FILE* is a file where the records will be read.
fp : file pointer
Random access to files
Random accessing of files in C language can be
done with the help of the following functions −
1) ftell ( )
2) rewind ( )
3) fseek ( )
ftell()
It returns the current position of the file pointer.
For example,
FILE *fp;
int n;
_____
_____
_____
n = ftell (fp);
ftell() is used for counting the number of
characters which are entered into a file.
rewind()
It makes file pointer move to beginning of the
file.
The syntax is as follows −
rewind (file_pointer);
fseek()
It is to make the file pointer point to a particular location in a
file.
The syntax is as follows −
fseek(file_pointer, offset, position);
Offset
The number of positions to be moved while reading or writing. If
can be either negative or positive.
Positive - forward direction.
Negative – backward direction.
Position
It can have three values, which are as follows −
0 – Beginning of the file.
1 – Current position.
2 – End of the file.
Question No. 1
Write a C program to read and display contents in a
file.
Program: To write content into a file
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("one.txt","w");
printf("Enter the line of text\n");
while((ch=getchar())!='\n')
{
fputc(ch,fp);
}
fclose(fp);
return 0;
}
Output
Program: To read content from a file
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("one.txt","r");
printf("The content in file is:\n");
while(!feof(fp))
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
return 0;
}
Output
Program: To read and display contents in a file
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("one.txt","w");
printf("Enter the line of text\n");
while((ch=getchar())!='\n')
{
fputc(ch,fp);
}
fclose(fp);
fp=fopen("one.txt","r");
printf("The content in file is:\n");
while(!feof(fp))
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
return 0;
}
Output
Question No. 2
Write a C program to copy the content of the file
‘one.txt’ to ‘two.txt’. Display the content of ‘two.txt’
in the console.
Program: To copy the content of the file ‘one.txt’ to
‘two.txt’
#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("one.txt","r");
fp2=fopen("two.txt","w");
while(!feof(fp1))
{
ch=fgetc(fp1);
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
Output
Program: To copy the content of the file ‘one.txt’ to
‘two.txt’.Display the content of ‘two.txt’ in the console.
#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("one.txt","r");
fp2=fopen("two.txt","w");
while(!feof(fp1))
{
ch=fgetc(fp1);
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
fp2=fopen("two.txt","r");
printf("The content in file is:\n");
while(!feof(fp2))
{
ch=fgetc(fp2);
printf("%c",ch);
}
fclose(fp2);
return 0;
}
Output
Question No. 3
Write a C program which computes the factorial of a
given number and write the result to a file named
factorial.
Program: C program which computes the factorial of a given
number.
#include<stdio.h>
int main()
{
int n,i,f;
printf("Enter the number\n");
scanf("%d",&n);
if(n==0)
{
printf("Factorial is 1\n");
}
else if(n<0)
{
printf("Factorial does not exist\n");
}
else
{
f=1;
for(i=n;i>=1;i--)
{
f=f*i;
}
printf("Factorial=%d\n",f);
}
return 0;
}
Program: C program which computes the factorial of a given
number and write the result to a file named factorial.
#include<stdio.h>
int main()
{
int n,i,f;
FILE *fp;
fp=fopen("Factorial.txt","w");
printf("Enter the number\n");
scanf("%d",&n);
if(n==0)
{
fprintf(fp,"Factorial is 1\n");
}
else if(n<0)
{
fprintf(fp,"Factorial does not exist\n");
}
else
{
f=1;
for(i=n;i>=1;i--)
{
f=f*i;
}
fprintf(fp,"Factorial=%d\n",f);
}
fclose(fp);
return 0;
}
Output 1
Output 2
Output 3
Thank you…….

You might also like