0% found this document useful (0 votes)
19 views

Pointer

The document discusses pointers in C programming. Pointers contain memory addresses as values and are used to access and manipulate data in memory. Pointers allow passing arrays and strings by reference rather than copying them. Pointers can point to variables, arrays, functions, and structures.

Uploaded by

ganeshanand2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Pointer

The document discusses pointers in C programming. Pointers contain memory addresses as values and are used to access and manipulate data in memory. Pointers allow passing arrays and strings by reference rather than copying them. Pointers can point to variables, arrays, functions, and structures.

Uploaded by

ganeshanand2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

UNIT – V

CHAPTER XI
POINTERS
11.1 INTRODUCTION
• A pointer is a derived data type in c. (iv) Pointers are helpful in traversing through
arrays and character strings. The strings
• Pointers contains memory addresses as
are also arrays of characters terminated by
their values.
the null character (‘\0’).
• A pointer is a variable whose value is the
(v) Pointers also act as references to different
address of another variable, i.e., direct
types of objects such as variables, arrays,
address of the memory location.
functions, structures, etc. In C, we use
• Like any variable or constant, you must pointer as a reference.
declare a pointer before using it to store
(vi) Storage of strings through pointers saves
any variable address.
memory space.
• Pointers can be used to access and
(vii) Pointers may be used to pass on arrays,
manipulate data stored in the memory.
strings, functions, and variables as
Advantages arguments of a function.
(i) Pointers make the programs simple and (viii) Passing on arrays by pointers saves lot of
reduce their length. memory because we are passing on only
(ii) Pointers are helpful in allocation and de- the address of array instead of all the
allocation of memory during the execution elements of an array, which would mean
of the program. passing on copies of all the elements and
Thus, pointers are the instruments thus taking lot of memory space.
dynamic memory management. (ix) Pointers are used to construct different
(iii) Pointers enhance the execution speed of a data structures such as linked lists, queues,
program. stacks, etc.
11.2 ACCESSING THE ADDRESS VARIABLE
• The operator & immediately preceding a #include <stdio.h>
variable returns the address of the variable #include <conio.h>
associated with it. void main()
Example {
p=&quantity; int x=125;
• Would assign 5000 (the location of float p=20.345;
quantity) to the variable p.
char a=‘a’;
• The & operator is a address operator.
clrscr();
• The & operator can be used only with a
simple variable or an array element. printf(“%d is stored at addr %u\n”,x,&x);
&125  pointing at constants printf(“%f is stored at addr %u\n”,p,&p);
int x[10]; illegal printf(“%c is stored at addr %u\n”,a,&a);
&x  pointing at array names getch();
&(x+y)  pointing at expressions }
• If x is an array then expression such as
&x[0] is valid.
DECLARING POINTER VARIABLES INITIALIZATION OF POINTER
Syntax VARIABLES
data_type *pt_name; • The process of assigning the address of a
variable to a pointer variable is known as
1. The * tells that the variable pt_name is a
initialization.
name of the pointer variable.
• All uninitialized pointers will have some
2. Pt_name needs a memory location.
unknown values that will be interpreted as
3. Pt_name points to a variable of type memory addresses.
data_type.
• They may not be valid addresses or they
Example may point to some values that are wrong.
int *p; • Once a pointer variable has been declared
• Declares the variable p as a pointer we can use the assignment operator to
variable that points to an integer data type. initialize the variable.
• The declarations cause the compiler to Example
alocate memory locations for the pointer 1. int q; 2. int q; 3. int x,*p=&x
variable p. int *p; int *p=&q
p=&q;
Illegal statement  int *p=&x, x;
• We can also define a pointer variable with
an initial value to NULL or 0.
int *p=null:
int *p=0;
11.3 POINTER FLEXIBILITY
• Pointers are flexible.
• We can make the same pointer to point to different data variables in different statements.
Example
int x, y, z, *p
……………
*p=&x;
……………
*p=&y;
……………
*p=&z;
……………
• We can also use different pointers to point to the same data variable.
Example
int x;
int *p1=&x;
int *p2=&x;
int *p3=&x;
…………..
• With the exception of NULL and 0, no other constant value can be assigned to a pointer variable.
11.4 ACCESSING A VARIABLE THROUGH ITS
POINTERS
#include <stdio.h>
• We can access the value of another
variable using the pointer variable. int main(void)
{
Steps: //normal variable
• Declare a normal variable, assign the int num = 100;
value.
• Declare a pointer variable with the //pointer variable
same type as the normal variable. int *ptr;
• Initialize the pointer variable with the //pointer initialization
address of normal variable.
• Access the value of the variable by ptr = &num;
using asterisk (*) - it is known //pritning the value
as dereference operator (indirection
operators). printf("value of num = %d\n", *ptr);
return 0;
}
EXAMPLE
#include <stdio.h> Output
void main() Value of x is 10
{
int x,y; 10 is stored at address 2996846848
int *ptr; 10 is stored at address 2996846848
x=10; 10 is stored at address 2996846848
ptr=&x;
298120448 is stored at address 2996846856
y=*ptr;
printf("Value of x is %d\n",x);
10 is stored at address 2996846852
printf("%d is stored at address %u\n",x,&x);
printf("%d is stored at address %u\n",*&x, &x);
New value of x =100
printf("%d is stored at address %u\n",*ptr,ptr);
printf("%d is stored at address %u\n",ptr,&ptr);
printf("%d is stored at address %u\n",y,&y);
*ptr=100;
printf("\nNew value of x =%d\n",x);
}
ILLUSTRATION OF POINTER EXPRESSION
Stage values in the storage cells and their address
x y ptr
Declaration

2996846848 2996846852 298120448 address


x=10
10
2996846848 2996846852 298120448 address
ptr=&x 10 2996846848

address

y=*ptr 10 10 2996846848

address

pointer to x

*ptr=100 100 10 2996846848


11.5 CHAIN OF POINTER
• Pointer to point to another pointer, thus • The pointer p2 is not a pointer to an
creating a chain of pointer. integer, but rather a pointer to an integer
pointer.
p2 p1 variable • We can access the target value indirectly
pointed to by pointer to a pointer by
applying the indirection operator twice.
address2 address1 value #include <stdio.h>
void main()
• The pointer variable p2 contains the
address of the pointer variable p1, which {
points to the location that contains the int x, *p1,**p2;
desired value. x=100;
• This is known as multiple indirections. p1=&x;
• A variable that is pointer to a pointer must p2=&p1;
be declared using additional indirection printf("pointer to pointer value %d",**p2);
operator symbol in front of the name. }
int **p2;
• The declaration tells the compiler that p2 Output
is a pointer to a pointer of int type.
pointer to pointer value 100
11.6 POINTER EXPRESSIONS
• Pointer variables can be used in • In addition to arithmetic operations ,
expressions the pointer can also be compared
Example using the relational operators.
• If p1 and p2 are properly declared and p1>p2
initialized pointers then the following p1==p2
statements are valid. p1 != p2
y= *p1 * *p2;  y=(*p1) * (*p2) • We may not use pointers in division
sum= sum + *p1; or multiplications.
z=5* - *p1/ *p2 (5* (-(*p1)))/(*p2); p1/p2
• There is blank space between / and p1 * p2
*p2 p1/3
*p2= *p2 + 10;
p1+4;
p2-2;
p1-p2;
p1++;
-p2;
sum += *p2;
Example printf("*p1 = %d\n",*p1);
printf("*p2 = %d\n",*p2);
#include <stdio.h> printf("z= %d\n",z);
int main() return 0;
{ }
int a, b,*p1, *p2,x,y,z; Output
a=10; Address of a = 71870892
b= 5; Address of b = 71870896
p1=&a; a= 10 b=5
p2=&b; x= 50 y=15
x= *p1 * *p2; a= 5 b=10
y= *p1 + *p2; *p1 = 5
printf("Address of a = %u\n",a); *p2 = 10
printf("Address of b = %u\n",b); z= 43
printf("a= %d\tb=%d\n",a,b);
printf("x= %d\ty=%d\n",x,y);
*p2= *p2 +5;
*p1= *p1-5;
z= *p1 * *p2 -7;
printf("a= %d\tb=%d\n",a,b);
11.7 POINTER INCREMENT & SCALE FACTOR
p1++;
• The pointer p1 to point to the next value of its type.
• If p1 is an integer pointer with an initial value, say 4020, then the operation p1++, the
value of p1 will be 4022.
• Ie, the value increased by the length of the data type that it points to.

char 1 byte
int 2 bytes
float 4 bytes
long int 4 bytes
double 8 bytes
11.8 POINTERS AND ARRAYS
• The address of &x[0] and x is the same. It's for(i = 0; i < n; ++i)
because the variable name x points to the first {
element of the array. /* Equivalent to scanf("%d", &x[i]); */
• &x[0] is equivalent to x. And, x[0] is equivalent scanf("%d", x+i);
to *x. // Equivalent to sum += x[i]
• Similarly, &x[1] is equivalent to x+1 and x[1] is sum += *(x+i);
equivalent to *(x+1). }
• &x[2] is equivalent to x+2 and x[2] is equivalent printf("Sum = %d", sum);
to *(x+2). return 0;
• Basically, &x[i] is equivalent to x+i and x[i] is }
equivalent to *(x+i). Output
Enter the value of n: 5
Example 1: Pointers and Arrays Enter number one by one
5
#include <stdio.h> 10
int main() 15
{ 20
int i, x[20], sum = 0,n; 25
Sum = 75
printf("Enter the value of n: ");
scanf("%d",&n);
printf("Enter number one by one\n");
Example :2 output
#include <stdio.h> Enter the value of n
int main()
5
{
Enter the array elements one by one
int *p,sum,i;
int n,x[10]; 1
printf ("Enter the value of n\n"); 2
scanf("%d",&n); 3
printf("Enter the array elements one by one\n"); 4
for (i=0;i<n;i++) 5
scanf("%d",&x[i]); Elements Value Address
p=x;
printf("Elements\t Value\t Address\n"); x[0]
for (i=0;i<n;i++) 1 2316341728
{ x[1] 2 2316341732
printf("x[%d] %d %u\n",i,*p,p);
sum +=*p; x[2] 3 2316341736
p++;
} x[3] 4 2316341740
printf("\n Sum = %d",sum);
x[4] 5 2316341744
printf("\n address of first element (&x[0]) =
%u",&x[0]);
Sum = 16
printf("\n p = %u",p);
address of first element (&x[0]) = 2316341728
return 0;
}
p = 2316341748
• Pointers can be used to manipulate two-dimensional arrays also.
• An two-dimensional array can be represented by the pointer expression as follows
• *(*(a+i)+j) or *(*(p+1)+j)
COLUMNS
0 1 2 3 4 5
0 p

1  p+1

R
2  p+2
O 3
W
S 4 4,0 4,3 p+4

5
6  p+6

*(p+4) *(p+4)+3
p  pointer to first row
p+i  pointer to ith row printf("\n\n");
*(p+i)  pointer to first element in the ith row }
*(p+i) +j  pointer to jth element in the ith // signal to operating system program ran fine
row return 0;
*(*(p+i)+j)  valu stored in the ith row and }
jth columns. Output
Example arr[2][3]=44Address of 0 th array 2692284448
#include<stdio.h> arr[0][0]=11
int main() arr[0][1]=22
{ arr[0][2]=33
int arr[3][4] = { {11,22,33,44}, arr[0][3]=44
{55,66,77,88},{11,66,77,44}}; Address of 1 th array 2692284464
int i, j; arr[1][0]=55
for(i = 0; i < 3; i++) arr[1][1]=66
{ arr[1][3]=88
printf("Address of %d th array %u \n",i , *(arr + i)); Address of 2 th array 2692284480
for(j = 0; j < 4; j++) arr[2][0]=11
{
arr[2][1]=66
printf("arr[%d][%d]=%d\n", i, j, *( *(arr + i) + j) );
arr[2][2]=77
}
arr[2][3]=44
11.9 POINTERS AND CHARACTER STRINGS
• C supports an alternate method to create #include <stdio.h>
strings using pointer variables of type #include <string.h>
char. int main ()
Example {
char *str= “Hello”; char name[25];
• This creates a string for the literal and then char *ptr;
stores its address in the pointer variable strcpy(name,"gaccbe");
str. ptr=name;
• The pointer str now points to the first while(*ptr !='\0')
character of the string “Hello” as {
printf("\n %c is stored at address %u",*ptr,ptr);
ptr++;
H e l l o \0 }
return 0;
}
str Output
g is stored at address 3432464000

We can also use runtime assignment for a is stored at address 3432464001


giving values to a string pointer.
c is stored at address 3432464002

char *str; c is stored at address 3432464003


str= “hello”; b is stored at address 3432464004

e is stored at address 3432464005


11.10 ARRAY OF POINTERS
Example #include <stdio.h>
const int MAX = 4;
char name[4][25];
int main ()
• The name is a table containing four {
names, each with maximum of 25 char *names[] = { “Anu", “Banu", “Chandru",
characters. “Deepak" };
int i = 0;
• The total storage requirements is 75 bytes.
for ( i = 0; i < MAX; i++)
• The individual strings will of equal {
lengths. printf("Value of names[%d] = %s\n", i, names[i] );
Example }
char *names[4] = { return 0;
}
“Anu",
“Banu", Output
“Chandru", Value of names[0] = Anu
Value of names[1] = Banu
“Deepak"
Value of names[2] = Chandru
}; Value of names[3] =Deepak
• Declares name to be an array of four
pointers to characters, each pointer
pointing to a particular name.
11.11 POINTERS AS FUNCTION ARGUMENTS
• Pointer as a function parameter is used to printf("After Swapping:\n\n");
hold addresses of arguments passed during printf("m = %d\n", m);
function call. printf("n = %d", n);
• This is also known as call by reference. return 0;
• When a function is called by reference any }
change made to the reference variable will void exchange (int *a, int *b)
effect the original variable. {
EXAMPLE int temp;
#include <stdio.h> temp = *a;
void exchange(int *a, int *b); *a = *b;
int main() *b = temp;
{ }
Output
int m = 10, n = 20;
m = 10
printf("m = %d\n", m);
n = 20
printf("n = %d\n\n", n); After Swapping:
swap(&m, &n); m = 20
n = 10
11.12 FUNCTIONS RETURNING POINTERS

• A function can return a single value by #include <stdio.h>


its name or return multiple values int* larger(int*, int*);
through pointer parameters. void main()
• A function can also return a pointer to {
the calling function. int a = 10;
• Local variables of function doesn't live int b = 20;
outside the function. int *p;
• They have scope only inside the p = larger(&a, &b);
function. printf("%d is larger",*p);
• Hence if you return a pointer connected }
to a local variable, that pointer will be int* larger(int *x, int *y)
pointing to nothing when the function {
ends. if(*x > *y)
return x;
Else
return y;
}
Output
20 is larger
11.13 POINTERS TO FUNCTIONS
• It is possible to declare a pointer pointing to Example
a function which can then be used as an
argument in another function. #include <stdio.h>
• A pointer to a function is declared as int sum(int x, int y)
follows, {
type (*pointer-name)(parameter) return x+y;
Example
}
int (*sum)(); legal declaration of pointer to
function int main( )
int *sum(); This is not a declaration of {
pointer to function. int (*fp)(int, int);
• A function pointer can point to a specific
function when it is assigned the name of that fp = sum;
function. int s = fp(10, 15);
int sum(int, int); printf("Sum is %d", s);
int (*s)(int, int);
return 0;
s = sum;
}
• s is a pointer to a function sum.
• sum can be called using function Output
pointer s along with providing the required 25
argument values.
s (10, 20);
11.14 POINTERS AND STRUCTURES
• We know that the name of an array stands • Its member can be access
for the address of its zero-th element.
ptr –>name ;
• Also true for the names of arrays of ptr –> no ;
structure variables.
ptr –> price;
Example The symbol “–>” is called the arrow
struct inventory operator or member selection
{ operator.
int no; • When the pointer ptr is incremented by
char name[30]; one (ptr++) :The value of ptr is actually
increased by sizeof(inventory).
float price;
• It is made to point to the next record.
} product[5], *ptr ;
• We can also use the notation
• The name product represents the address
of the zero-th element of the structure (*ptr).no;
array. • When using structure pointers, we should
• ptr is a pointer to data objects of the type take care of operator precedence.
struct inventory. • Member operator “.” has higher
• The assignment precedence than “*”.
ptr = product ; • ptr –> no and (*ptr).no mean the same
thing.
will assign the address of product [0] to ptr.
• ptr.no will lead to error.
• The operator “–>” enjoys the struct book b1 = { "Programming in C",
highest priority among operators "E Balagurusamy", 2 } ;
• ++ptr –> no will increment roll, struct book *ptr ;
not ptr. ptr = &b1 ;
• (++ptr) –> no will do the intended printf ( "\n%s %s edition %d ", b1.name,
thing. b1.author, b1.edn ) ;
Example printf ( "\n%s %s edition %d", ptr-
void main () >name, ptr->author, ptr->edn ) ;
{ }
struct book Output
{ Programming in C E Balagurusamy edition 2
char name[25]; Programming in C E Balagurusamy edition 2
char author[25];
int edn;
};
UNIT – V
CHAPTER XII
FILES
12.1 INTRODUCTION
• File Handling is the storing of data in a High-level I/O functions
file using a program. Function Description
• the programs store results, and other data
of the program to a file using file fopen() function is used to create a new file or open
handling in C. an existing file in C.
• Also, we can extract/fetch data from a file fclose() Closes as a file
to work with it in the program.
fprintf ( ) write data into a file
File operations
fscanf ( ) read data from a file
1. Naming a file
2. Opening an existing file putc ( )/ write a character into a file
fputc()
3. Reading data from an existing file
getc ( ) read a character from a file
4. Writing data to a file
/fgetc()
5. Closing the file
putw ( ) write a number into a file
Two ways to perform the operations in c.
1. low-level i/o and uses UNIX getw ( ) read number from a file

2. High-level i/o and uses functions in C’s fputs ( ) write a string into a file
standard library. fgets ( ) read a string from a file
fread() read an entire record from a file
fwrite() write an entire record into a file
12.2 DEFINING AND OPENING A FILE
• To store data in a file in the secondary 1. fp as a file pointer to the data type FILE.
memory, we must specify 2. Filename- the file opened in the named
1. Filename filename and assign an identifier to the
FILE type pointer fp.
2. Data structure
3. Mode- It is a string (usually a single
3. Purpose
character ) that specifies the mode in
• file_name − It is a string that specifies the which the file is to be opened.
name of the file that is to be opened or
“r” − open for reading
created using the fopen method.
“rb” − open for reading in binary mode
It may contain two parts
“w” − open for writing only
A primary name and an optional period
with the extension. “wb” − open for writing in binary mode
• Data structure of a file is defined as FILE “a” − open for append only
in the library of standard I/O functions “ab” − open for append in binary
definition. “r+” − open for reading and writing both
• Purpose-what we want to do with the file. “rb+” − open for reading in binary mode
Example “w+” − open for writing and reading
FILE *fp; “wb+” - open for writing and reading in
fp = fopen(“file_name”, “mode”); binary mode
“a+” − open for read and append
“ab+” − open for read and append in binary
12.3 CLOSING A FILE
• A file must be closed as soon as the all • Once the file is closed, its file pointer can
operations are completed. be reused for another file.
fclose(file_pointer); • All files are closed automatically
• Close file associated with the FILE pointer whenever a program terminates.
file_pointer.
Example
----------
----------
FILE *fp1,*fp2;
fp1=fopen(“INPUT”,”w”);
fp2=fopen(“OUTPUT”,”r”);
----------
----------
fclose(fp1);
fclose(fp2);
12.4 INPUT/OUTPUT OPERATIONS ON FILES
The getc() and putc() function #include <stdio.h>
• The file is opened with mode w and int main()
filepointer fp1. {
putc(c,fp1); FILE *fp;
• Writes a character contained in the char c;
character variable c to the file associated printf("Data Input\n");
with FILE pointer fp1.
fp=fopen("INPUT.TXT","w");
c=getc(fp2);
while ((c=getchar()) != EOF)
• Reads a character from the file whose file
pointer is fp2. putc(c,fp);
• The file pointer moves by one character fclose(fp);
position for every operations of getc() and printf("Data Output\n");
putc(). fp=fopen("INPUT.TXT","r");
Example while ((c=getc(fp))!=EOF)
printf("%c",c);
fclose(fp);
return 0;
}
get() and putw() functions printf("Data Output\n");
• Integer oriented functions. f1=fopen("DATA.TXT","r");
• Used to read and write integer values. while ((n=getw(f1))!=EOF)
putw(integer,fp); printf("%d",n);
integer_variable=getw(fp); fclose(f1);
Example return 0;
#include <stdio.h> }
int main() Output
{ Data file
FILE *f1; 1
int n,i; 2
printf("Data file\n"); 3
f1=fopen("DATA.TXT","w"); 4
for (i=1;i<=10;i++) 5
{ 6
scanf("%d",&n); -1
if(n== -1) break; Data Output
putw(n,f1); 1 2 3 4 5 6
} .
fclose(f1);
fscanf() and fprintf() functions
printf("Item Name no price Quantity\n");
• These functions are used performed I?O for(i=1;i<=3;i++)
operations on files.
{
fprintf(fp,”control string”,list); scanf("%s %d %f %d", item, &n, &price, &qty);
fscanf(fp,control string”,list); fprintf(fp,"%s %d %f %d",item,n,price,qty);
• Where fp is a file pointer associate with a }
file that has been opened for writing. fclose(fp);
• The control string contains output printf("Data Output\n");
specifications for the items in the list. fp=fopen(filename,"r");
• The list may include variables, constants printf("Item Name no price Quantity\n");
and strings. for(i=1;i<=3;i++)
Example {
fscanf(fp,"%s %d %f %d",item,&n,&price,&qty);
#include <stdio.h>
printf("%s %d %f %d\n",item,n,price,qty);
int main()
}
{ fclose(fp);
FILE *fp; int n,qty,i; return 0;
float price,value; }
char item[10],filename[10]; Output
printf("Input file name\n");
scanf("%s",filename);
fp=fopen(filename,"w");
printf("input inventory details\n");
Output

Input file name


pen
input inventory details
Item Name no price Quantity

note
1
50.50
100
pencil
2
56.90
290
paper
3
120.00
500
Data Output
Item Name no price Quantity

note 1 50.500000 100


pencil 2 56.900002 290
paper 3 120.000000 500
12.5 ERROR HANDLING DURING I/O
OPERATIONS
Error situations
1. Trying to read beyond the end-of-file mark.
2. Device overflow
3. Trying to use a file that has not been opened.
4. Trying to perform an operations on a file, when the file is opened for another type of
operations
5. Opening a file with an invalid filename
6. Attempting to write to a write-protected file.
• foef-use to test for an end of file condition.
• ferror-reports status of the file indicated.
Example for(i=10;i<=100;i+=10)
#include <stdio.h> {
int main() n=getw(fp2);
{ if (feof(fp2))
char *filename; {
FILE *fp1,*fp2; printf("Run out of data\n");
int i,n; break;
fp1=fopen("TEST.TXT","w"); }
for (i=10;i<=100;i+=10) else .
putw(i,fp1); printf("%d\n",n);
fclose(fp1); }
printf("Input filename"); fclose(fp2);
s:scanf("%s",filename); return 0;
if ((fp2=fopen(filename,"r"))== NULL) }
{
printf("Cannot open the file\n");
printf("Try again\n");
goto s;
}
Else
Output
Input filenametet
Cannot open the file
Try again
TEST.TXT

10
20
30
40
50
60
70
80
90
100
12.6 RANDOM ACCESS FILE
• functions for random access file
processing. value meaning
1. fseek() 0 Beginning of the file
2. ftell() 1 Current position
3. rewind()
2 End of the file
fseek()
This function is used for seeking the .
pointer position in the file at the specified
Statement Meaning
byte.
Syntax fseek(fp,0l,0); Got o the beginning
fseek( file_ptr, offset, position); fseek(fp,0l,1); Stay at the current position
file_ptr :pointer to the file concerned.
fseek(fp,0l,2); Go to the end of the file
offset: is a number or variale of type long.
fseek(fp,m,0); Move to (m+1)th byte in the
the no. positions (bytes) to be moved
file
from the location specified by position.
fseek(fp,m,1); Go forward by m bytes
position: is an integer number.
The position can take one of the three values. fseek(fp,-m10); Go backward by m bytes
from the current position
The offset may be positive, meaning move
fseek(fp,-m,2); Go backward by m bytes
forwards, or negative, meaning move
from the end
backwards
Example printf("\nThe current position of the file
#include <stdio.h> pointer is: %ld\n", ftell(fp));
int main () rewind(fp);
{ printf("The current position of the file pointer
FILE *fp; is: %ld\n", ftell(fp));
int c; printf("After rewrite the contents\n");
fp = fopen("OUTPUT.txt","w+"); printf("Read the Random Access File\n");
fputs("Random Access file example", fp); while(1)
fseek( fp, 0, SEEK_SET ); {
printf("Random Access file contains\n"); c = fgetc(fp);
while(1) if( feof(fp))
{ {
c = fgetc(fp); break;
if( feof(fp)) }
{ printf("%c", c);
break; }
} fclose(fp);
printf("%c", c); return(0);
} }
fputs("\nC Programming E Balagurusamy", fp);
fputs("\nsecond edition", fp);
Output
Random Access file contains
Random Access file example
The current position of the file pointer is: 70
The current position of the file pointer is: 0
After rewrite the contents
Read the Random Access File
Random Access file example
C Programming E Balagurusamy
second edition
12.7 COMMAND LINE ARGUMENTS
What is a command line argument? #include <stdio.h>
void main( int argc, char *argv[] )
• It is a parameter supplied to a program when the
{
program is invoked. FILE *fp;
• This parameter may represent a filename the int i;
program should process. Char word[15];
• The command line arguments are handled using fp=fopen(argv[1],"w");
main() function arguments where argc refers to printf("No. of arguments in command line =%d\n",argc);
for(i=2;i<argc;i++)
the number of arguments passed, and argv[] is a
{
pointer array which points to each argument
fprintf(fp,"%s",argv[1]);
passed to the program. }
• In order to access the command line arguments, fclose(fp);
we must declare the main() function and its printf("contents of %s file \n",argv[1]);
parameters are fp=fopen(argv[1],"r");
main(int argc,char *argv[]) for(i=2;i<argc;i++)
{
{ fscanf(fp,"%s",word);
------------- printf("%s",word);
------------- }
fclose(fp);
}
printf("\n\n");
for(i=0;i<argc;i++)
printf("%s\n",argv[i]);
}
References
1. 1. E. Balagurusamy, ”Programming in ANSI C”, Seventh Edition, McGraw Hill Education
India Private Ltd, 2017.
2. . https://www.tutorialspoint.com/cprogramming/
3. https://ecomputernotes.com/what-is-c/function-a-pointer/advantages-of-using-pointers
4. https://www.includehelp.com/c/accessing-the-value-of-a-variable-using-pointer-in-c.aspx
5. https://www.programiz.com/c-programming/c-pointers-arrays
6. https://www.studytonight.com/c/pointer-with-function-in-c.php

You might also like