PROGRAMMING IN C
Module 4 EST 102
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
1) Define 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.
eg : int # P-
-
2) Symbols used in Pointer
Symbol
-addres Name Description
?
Address Determine the address
I & (Ampersand sign)
Operator of a variable
Indirection Access the value
(Asterisk sign)
* Operator of an address
↓ at
value
=
3) How to Declare and Initialize 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,
int a;
data_type *pointer_variable;
pointer_variable=&variable_name;
2000
eg : int
* Declar
100
p =& a > Initidization
D B
=
100 ;
-- -
Printf( Gd", a) Dip
&
=
For example,
int a;
Printf Ptr)
( "Yod" , * = 10
a=10;
int *ptr; //declaration
ptr = &a; //initialization value of
We can also combine the initialization with the declaration.
int a=10; caddres pointed
int *ptr = &a; by P)
= value (a) = ) 10
4) Write a C program to add two numbers using pointers.
Program Gov
%1
10
#include<stdio.h>
int main() %
{
int a,b,*p,*q,sum;
Corby wo
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
p=&a;
q=&b;
address printel
atC
sum=*p+*q;
printf("Sum=%d\n",sum);
return 0;
*P =value osP)
}
=
value at
(1000) 10 =
Output
Enter two numbers
10
6
Sum=16
5) Write a C program to swap two numbers using pointers.
normal b pointes
I
a -
temp = a =)
temp
Program a = b =b
* m
*
Y
=
#include<stdio.h>
int main() b = temp a
{
*n = temp
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
6)Pointer to a Pointer (Chain of Pointers)
J
It is possible to make pointer to point to another pointer.
espoint a
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.
1001 2000
E Mod B
-y/I
2008
a
-
b
-
pointes T j
int *D
buda nu
&b
C
=
int **C;
7) What will be the output of the following C program?
you you
rol B
#include<stdio.h> 2000
int main()
{
int a,*p,**q;
a=120;
it
120!
p=&a;
value o a =
q=&p;
- avai---at #P
printf("Value of a=%d\n",a);
value 120E
=
printf("Value available at *p=%d\n",*p); -
printf("Value available at **q=%d\n",**q); value avi--a = 120
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
8) Write a C program to find sum of n numbers using pointers.
&
↑
&
&
-
n =
4
Program
#include<stdio.h>
int main()
{
Tolso)
int a[10],i,n,sum,*ptr;
02 3
prentity
printf("Enter the limit\n");
scanf("%d",&n); Pau
neilt printf("Enter the elements\n");
= indecsum=0;
ptr=a; //ptr=&a[0]; sum
= O
I
for(i=0;i<n;i++) a
ptr
=
{
scanf("%d",&a[i]);
-
I
sum=sum+*ptr;
}
ptr++;
aso]
at &
printf("Sum=%d\n",sum);
return 0;
}
Output
Enter the limit
~
3
Enter the elements
10 -
-
20
30 ~
Sum=60
9) Define NULL Pointer
z
=
macro
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.
10) How to declaring NULL pointer follows:
int *pointer_var;
-
pointer_var=NULL; -
-
or
int *pointer_var = NULL;
or
int *pointer_var;
-
pointer_var=0;
-
or
~
int *pointer_var = 0;
eg : int *p=NULL: -
11) Advantages of Pointer
Less time in program execution -
Working on the original variable -
With the help of pointers, we can create data structures (linked-list, stack, queue). -
Returning more than one values from functions -
Searching and sorting large data very easily
-
Dynamically memory allocation
~
↓
allocation of memory
during son time
12) Disadvantages Pointer
Sometimes by creating pointers, such errors come in the program, which is very difficult to diagnose. -
Sometimes pointer leaks in memory are also created. -
If extra memory is not found then a program crash can also occur. -
Files
13) Types of files in c
name
↑
tal-
Text Files -
-
Binary Files
~
-
1. Text Files
in
~
- A text file contains data in the form of ASCII characters and is generally used to store a stream of characters. 2
-
- Each line in a text file ends with a new line character (‘\n’).
-
-It can be read or written by any text editor.
-
-They are generally stored with .txt file extension.
Text files can also be used to store the source code.
2. Binary Files ~
-A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They contain data
- -
-
-
-that is stored in a similar manner to how it is stored in the main memory.
The binary files can be created only from within a program and their contents can only be read by a program.
More secure as they are not easily readable.
They are generally stored with .bin file extension.
-
pointed
file ~
14) Need for File Handling in C
-
v 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.
15) what are the File Operations possible in C ~
X X X 4 -
(fopen with attributes as “a” or “a+” or “w” or “w++”) -
Opening an existing file
-
(fopen)
Reading from file
-
(fscanf or fgets)
-
-
Writing to a file
-
(fprintf or fputs)
- -
Moving to a specific location in a file
(fseek, rewind)
--
Closing a file
-
(fclose)
16) Declaring a file pointer
This structure declares within the header file stdio.h.
-
-
The declaration of the file pointer made as follows,
-
-
i FILE *fp;
=>
fp is the name of the file pointer which is declared as a pointer to a structure of type FILE.
- -
17) How to Open a file for creation and edit
# i
Yakt" "W
2)
,
fp=fopen("filename","mode");
--
-
If the call to the fopen() function is successful, the function returns a pointer of type FILE.
If the file cannot open for some reason, fopen() returns a NULL pointer. ·
-
-
18) File Opening Modes in C
conten t
already exist, erase on
MODE DESCRIPTION
~ r open text file for reading
if writing
- w truncate to zero length or create text file for writing =
create new fill For
wx create text file for writing ere
a append; open or create text file for writing at end-of-file
L
- rb open binary file for reading
- wb truncate to zero length or create binary file for writing
wbx create binary file for writing
~ ab append; open or create binary file for writing at end-of-file
r+ open text file for update (reading and writing)
w+ truncate to zero length or create text file for update
w+x create text file for update
a+ append; open or create text file for update, writing at end-of-file
r+b or rb+ open binary file for update (reading and writing)
w+b or wb+ truncate to zero length or create binary file for update
w+bx or wb+x create binary file for update
a+b or ab+ append; open or create binary file for update, writing at end-of-file
19) Closing a file
-
3) 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.
=>
=
20) List the different file handling functions in C
E&
NO. FUNCTION DESCRIPTION
1. fopen() Use to open new or existing file
2. fprintf() Use to write data into the file
3. fscanf() Use to read data from file ~
4. fputc() Use to write character to a file
-
5. fgetc() Use to read character from a file
6. fputs() Use to write a null terminated string to a file
7. fgets() Use to read a null terminated string from a file ~
8. fclose() Use to close the file -
21) Compare and contrast feof(),fwrite() and fread() functions
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,
Ap
-
feof(fp);
-
where,
-OF
-
fp – file pointer - Stop
- -
z - -
-
-
W
1n =
D
=
123 123
-
-
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
= 2
n
12) 123
z -
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
22) Compare sequential and random access in file
=> cassette
ECDDrive
ar pendlie
23) How to implement random accesss in C
Random access to files
Random accessing of files in C language can be done with the help of the following functions −
ftell ( ) -
rewind ( ) -
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.
--
↑
FP
It
actyl-
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);
--
por fo at)
I
O -YUMF
-
-> -
-
Offset -
The number of positions to be moved while reading or writing.
-
If can be either negative or positive. -
- Yu --
-
Positive - forward direction.
Pos ,
Negative – backward direction. L
-
Position
It can have three values, which are as follows −
0 – Beginning of the file. --
①
1 – Current position. -
- ud
en
2 – End of the file. - posit
= 2
24) Write a C program to write contents to a file.
Program
#include<stdio.h>
int main()
{ - morning
(good
FILE *fp; - for
char ch; -
fp=fopen("one.txt","w");
~
z -
printf("Enter the line of text\n");
-
while((ch=getchar())!='\n') L
S
S
{
fputc(ch,fp);
}
fclose(fp);
return 0;
}
25) Write a C program to read contents from a file.
#include<stdio.h>
int main()
will travel
{
FILE *fp; > T
Feend
-
char ch;
fp=fopen("one.txt","r"); reaf
EOF
i
printf("The content in file is:\n");
while(!feof(fp)) M
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
return 0;
}
26) Write a C program to write and read contents from a file.
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("one.txt","w");
printf("Enter the line of text\n");
write while((ch=getchar())!='\n')
{
fputc(ch,fp);
}
I
fclose(fp);
&fp=fopen("one.txt","r");
-
printf("The content in file is:\n");
read
while(!feof(fp))
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
return 0;
}
27) 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.
#include<stdio.h>
int main() one Hill
{ - -Ewotcl-
FILE *fp1,*fp2;
char ch;
- fp1=fopen("one.txt","r");
-fp2=fopen("two.txt","w");
while(!feof(fp1))
E
{
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))
real[
{
ch=fgetc(fp2);
printf("%c",ch);
}
fclose(fp2);
return 0’
}
28) Write a 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)
{ I
fprintf(fp,"Factorial is 1\n");
} --
else if(n<0)
Addi Fam
I
{
fprintf(fp,"Factorial does not exist\n"); -
fupen
Wil
} -
else
Ep =
Alt"
"Factorial
{
f=1; I
for(i=n;i>=1;i--) 2
code
{
E
}
f=f*i;
- red
fprintf(fp,"Factorial=%d\n",f); -
&
} - - - -
}
fclose(fp); -
return 0;
3
Frosh (fP)-
S
THANK YOU