Pointers, Structures, Files
Pointers, Structures, Files
Introduction to pointers
C provides the important feature of data manipulations with the address of
the variables, the execution time is very much reduced such concept is possible
with the special data type called Pointers.
Definition:
A pointer is a variable which stores the address of another variable.
Features of pointers:
Pointers save the memory space.
Execution time with pointer is faster because data is manipulated with the
address i.e; direct access to memory location.
The memory is accessed efficiently with the pointers. The pointers assign the
memory space and can be released after use. Dynamically memory is
allocated.
Pointers are used with data structures. They are useful for representing 2-d
and multidimensional arrays.
It reduces the length & complexity of programs.
It increases the execution speed and thus reduces the program execution
time.
Pointers can be used to pass information back and forth between a function.
In particular, pointers provide a way to return multiple data items from a
function via function arguments.
Pointers are also closely associated with arrays and therefore provide an
alternative way to access individual array elements.
Pointers are used in file handling.
The computer memory is a sequential collection of storage cells.
Declaration:
datatype *ptr_name;
This tells the compiler three things about the variable ptr_name.
1. The * tells that the variable ptr_name is a pointer variable and it stores address
of a variable of given datatype.
2. ptr_name needs a memory location.
3. ptr_name points to a variable of type datatype.
Ex:
int *p;
Declares the variable p as a pointer variable, that points to an integer data type.
Remember that the type int refers to the datatype of the variable being pointed to
by p and not the type of the pointer.
Similarly
float *x;
int x=10;
int *p=&x;
A pointer can point to only its intended datatype address location. For example,
integer pointer cannot point to floating point variable’s address location.
Accessing a variable through its pointer
This statement instructs the system to find a location for the integer variable ‘a’ and
puts the value 50 in that location.
Let us assume that the system has chosen the address location 2000 for a.
printf(“a=%d address=%u\n”a, &a);
output:
a=50 address=2000
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,x;
clrscr();
x=10;
p=&x;
printf("\n Value of x is %d", x)
printf("\n address of x is %u", &x)
printf("\n address stored in p(value of p) is %u", p)
printf("\n Value present at address stored in p (value of x) is %d", *p)
printf(“ \n *(&x):%d is equal to x:%d”,*(&x),x);
printf(“ \n &x:%u is equal to p:%u”, &x, p);
getch();
}
OUTPUT:
Value of x is 10
address of x is 504
address stored in p(value of p) is 504
Value present at address stored in p (value of x) is 10
*(&x):10 is equal to x: 10
&x:504 is equal to p:504
Pointer arithmetic
Pointer arithmetic actually moves the pointer reference by an arithmetic operation.
i.e. addition and subtraction.
Pointer arithmetic also called as address arithmetic. It allows the following
operations
Valid Pointer arithmetic Operations:-
1) A pointer can be assigned to another. The effect of this operation is to make
the pointers point o the same object.
2) A pointer can be incremented or decremented.
3) Integers can be added or subtracted with pointers i.e; pointer moves forward
or backward directions.
4) Two pointers can be subtracted from one another provided that they are
pointing to the same array.
Invalid Pointer arithmetic Operations:
1. Adding, Multiplying and dividing two pointers
2. Shifting, masking pointers.
3. Addition of float or double to pointers
4. Assignment of a pointer of one type to a pointer of another type.
base address
Here 'a' is a pointer that points to the first element. so the value of a is 1000
there fore a=&a[0]=1000
If we declare 'p' is an integer pointer, then we can make the pointer p
to point to the array 'a' by the following assignment.
int *p;
p=&a[0]; // equal to p=a;
Now we can access every value of a using p++(or)p+1 to move one element to
another.
The relationship between p and a is shown below.
p+0 = &a[0]=1000//1000+0
p+1 = &a[1]=1002//1000+1*(sizeof(int))
p+2 = &a[2]=1004//1000+2*(sizeof(int))
p+3 = &a[3]=1006//1000+3*(sizeof(int))
p+4 = &a[4]=1008//1000+4*(sizeof(int))
When handling arrays instead of using array indexing, we can use pointer to
access array elements. Note that *(p+k) gives the value of a[k]. Pointer accessing
method is much faster than array indexing.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
int *p=a;
clrscr();
printf("a[0]=%u",&a[0]);
printf("\na=%u",a);
printf("\n&a[0]=%u",p);
getch();
}
Program: Write a program to accept and display array elements using pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i;
int *p=&a[0];
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
printf("Given array elements:");
for(i=0;i<n;i++)
{
printf("%5d",*(p+i));
}
getch();
}
POINTER TO A POINTER
A pointer ‘p1′ can also point to another pointer ‘p2′ of same datatype
which is called as pointer to pointer. In memory, the three variables can be
visualized as :
example :
#include<stdio.h>
int main(void)
{
char **ptr = NULL;
char *p = NULL;
char c = 'd';
p = &c;
ptr = &p;
printf("\n c = [%c]\n",c);
printf("\n *p = [%c]\n",*p);
printf("\n **ptr = [%c]\n",**ptr);
return 0;
}
Character Pointers , Pointers and Strings
A string constant, written as
"I am a string"
is an array of characters. In the internal representation, the array is terminated with
the null character ’\0’ so that programs can find the end. The length in storage is
thus one more than the number of characters between the double quotes.
If pmessage is declared as
char *pmessage;
pmessage = "now is the time";
assigns to pmessage a pointer to the character array. This is not a string copy; only
pointers are involved.
char amessage[] = "now is the time"; /* an array */
char *pmessage = "now is the time"; /* a pointer */
amessage is an array, just big enough to hold the sequence of characters and ’\0’
that initializes it. On the other hand, pmessage is a pointer, initialized to point to a
string constant.
Suppose we wish to store “HELLO”.
Different ways are shown below:
char str[ ] = "HELLO" ;
char *p = "HELLO" ;
There is a difference in usage of these two forms. For example, we cannot assign a
string to another, whereas, we can assign a char pointer to another char pointer.
This is shown in the following program.
Example
main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
Also, once a string has been defined it cannot be initialized to another set of
characters. Unlike strings, such an operation is perfectly valid with char pointers.
main( )
{
char str1[ ] = "Hello" ;
char *p = "Hello" ;
str1 = "Bye" ; /* error */
p = "Bye" ; /* works */
}
Unlike other pointers, character pointers doesn’t require indirection operator (*) to
access the value at the address stored in the pointer. We can directly use the name
of the pointer to access the value.
VOID POINTER
Void pointer can point to any type of data.
A pointer which can be assigned to any type of pointer is called a void
pointer.
It is also called as generic pointer.
Type casting of the void pointer to the required type is essential to access the
data which it points to.
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
void *p;
int i=5;
char c='a';
float f=3.14;
clrscr();
p=&i;
printf("\nValue at address stored in p is %d",*(int *)p);
p=&c;
printf("\nValue at address stored in p is %c",*(char *)p);
p=&f;
printf("\nValue at address stored in p is %f",*(float *)p);
getch();
}
OUTPUT:
Value at address stored in p is 5
Value at address stored in p is a
Value at address stored in p is 3.14
Funcion Task
malloc Allocates requested size of bytes and returns a pointer to the first
byte of the allocated space.
calloc Allocates space for requested array of elements, and returns a
pointer to the first byte of the allocated space.
realloc Modifies the size of previously allocated space.
free Frees previously allocated space.
malloc():-
A block of memory of specified size may be allocated and a void pointer is returned
by using this function.
This void pointer can be assigned to any type of pointer.
Syntax:- ptr=(cast_type *)malloc(byte_size);
ptr is pointer of type cast_type. Byte_size is requested memory space for
allocation in bytes.
Example:- int *p;
p=(int *)malloc(sizeof(int)); //for 1 location
p=(int *)malloc(n*sizeof(int)); //for n locations
calloc():-
Allocates multiple blocks of memory such as arrays, structures, etc. and returns a
void pointer with the address of the first byte location.
Syntax: :- ptr=(cast_type *)calloc(n, element_size);
ptr is pointer of type cast_type. element_size is size of requested type. n is
no. of the elements of the required type.
eg:
int *p;
p=(int *)malloc(sizeof(int)); //for 1 location
p=(int *)realloc(p,5*sizeof(int));
Note: Memory allocation may fail and in such cases a null pointer is returned and in
case of realloc if it is unsuccessful, the original block is lost.
free:
Releases the allocated unused space can be done by using free() function.
Syntax: free(ptr);
Example:
free(ptr);
Command-line arguments
The C language provides a method to pass parameters to the main() function. This
is typically accomplished by specifying arguments on the operating system
command line (console).
The prototype for main() looks like:
void main(int argc, char *argv[])
{
…
}
There are two parameters passed to main().
The first parameter is the number of items on the command line (int argc).
The second parameter passed to main() is an array of pointers to the
character strings containing each argument (char *argv[]).
For example, at the command prompt:
test_prog 1 apple orange 4096.0
There are 5 items on the command line, so the operating system will set argc=5 .
The parameter argv is a pointer to an array of pointers to strings of characters, such
that:
argv[0] is a pointer to the string “test_prog”
argv[1] is a pointer to the string “1”
argv[2] is a pointer to the string “apple”
argv[3] is a pointer to the string “orange”
argv[4] is a pointer to the string “4096.0”
and argc is 5
Explanation
line 4 : we check if the user passed two arguments to the program. We actually
need two arguments but in C the first argument ( argv[0] ) is the name of our
program, so we need two more.
line 5 : If the user didn't pass two arguments we print the user to enter arguments
properly and exit.
line 10 : We display the arguments entered by user.
C program prints the number and all arguments which are passed to it.
#include <stdio.h>
void main(int argc, char *argv[])
{
int c;
printf("Number of command line arguments passed: %d\n", argc);
}
Dangling Memory / Dangling Pointers
Dangling pointers arise when an object is deleted or deallocated, without modifying
the value of the pointer, so that the pointer still points to the memory location of
the deallocated memory.
The pointer still points to the same location in memory even though the reference
has since been deleted and may now be used for other purposes.
void func()
{
char *dp = malloc(A_CONST);
/* ... */
free(dp); /* dp now becomes a dangling pointer */
dp = NULL; /* dp is no longer dangling */
/* ... */
}
OUTPUT
OUTPUT
UNIT V
ENUMERATED, STRUCTURE AND UNION TYPES
Arrays are used to store similar type of elements, whereas structures are
used to store different type of data items.
A structure is a collection of one or more variables, possibly of different
types, grouped together under a single name for convenient handling.
Using structures we can define our own data type. So structures are also
called as user defined datatype.
Structure Definition:
Structures must be defined first, for their format i.e. template which can be later
used to declare structure variables.
Syntax:
struct tag_name
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
};
For example:
struct emp_info
{
int emp_id;
char nm[30];
int age;
float sal;
};
Note the above example structure emp_info is not declaring any structure variable;
it is just a template to represent information as below.
Integer
Array of 30 Characters
Integer
Float
Structure Declaration:
we can declare structure variables of that type. Declaration includes the following
elements:
The keyword “struct”.
The structure tag name.
List of variable names separated by commas.
A terminating semi colon.
Syntax:
For Example:
struct emp_info e1,e2,…en;
A structure variable can also be declared along with its definition as shown below
Syntax:
struct tag_name
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
} structure_var_name1;
Example:
struct emp_info
{
char emp_id[10];
char nm[30];
int age;
float sal;
}e1,e2;
Syntax:
struct
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
}structure_var_ name1,structure_var_name2,…,structure_var_namen;
For example:
struct
{
char emp_id[10];
char nm[30];
int age;
float sal;
} e1,e2,…en;
For example:
struct emp_info
{
char emp_id[10];
char nm[30];
int age;
float sal;
} e1,e2,…en;
Structure Initialization:
A structure can be initialized by following its definition
Syntax:
struct tag_name svar={val1,val2,….,valn};
Example:
struct emp_info e1={1,”Ram”,22,30000};
Such initialization of structure variable is possible along with declaration during
definition also.
Syntax:
struct tag_name
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
}structure_var_ name1={val1,val2,….,valn};
For example:
struct emp_info
{
int emp_id;
char nm[30];
int age;
float sal;
} e1={1,”Ram”,22,30000};
Two structure variables of same type can be copied the same way as ordinary
variables.
If s_var1 and s_var2 are structure variables of same type then s_var2 can be
assigned to s_var1 as follows.
s_var1=s_var2; //valid
Similarly two structure variables can also be checked directly for equality or
inequality.
These are the only operations which are permitted directly on the structure
variables.
Array of Structures:
Syntax:
Example:
e[0].id=1;
strcpy(e[0].name,”Ram”);
e[0].age=22;
e[0].sal=30000;
s.roll_no=1;
[Link][0]=90;
[Link][1]=90;
[Link][2]=95;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
Example :
struct student
{
int rno;
char nm[50];
struct
{
int dd;
int mm;
int yyyy;
}dob;
}s;
The members which are inside the inner structure can be accessed as follow :
[Link];
[Link];
[Link];
cno read_complex_no()
{
cno a;
printf("\n Enter real and imaginary parts of the complex no.s\n");
scanf("%d%d",&[Link],&[Link]);
return a;
}
void print_complex_no(cno a)
{
printf("\n %d+i%d\n",[Link],[Link]);
}
ptr_name=&s_var;
The members of the structure variable can be accessed through the pointing
pointer also. For this we need a special operator called “arrow operator” ->.
ptr_name->member1=val1;
ptr_name->member2=val2;
.
.
.
ptr_name->membern=valn;
The paranthesis are required around *ptr, because period operator is more priority
than indirection operator.
Self-referential structures:
Syntax:
struct tag_name
{
type member1;
type member2;
.
.
type membern;
struct tag_name *next;
};
struct node
{
int data; /* points to the data */
struct node *next; /* next data item */
};
[Link]=10;
[Link]=20;
[Link]=&n2;
It is illegal for a structure to contain an instance of itself, but struct node *next;
declares next to be a pointer to a node type, not a node itself.
The self- referential structures are used in creating various data structures. For
example: linked lists, trees, graphs etc.
Size of a Structure:
The size of the structure is the total size occupied by the individual membes of the
structure.
The size of structure can be found directly by using the sizeof operator over its
type.
struct tagname s_var;
sizeof(struct tagname); gives the size occupied by any structure variable of this
type
or
sizeof(s_var); gives the size occupied by the structure variable
Example:
struct emp_info
{
int id;
char name[100];
int age;
float sal;
};
struct emp_info e1;
sizeof(struct emp_info) gives 108 (2+100+2+4) bytes.
sizeof(e1) is also same.
Unions:
Unions are a concept borrowed from structures.
The syntax of unions is same as structures. The major difference between structure
and union is in terms of storage.
Syntax of union
union tag_name
{
datatype1 member1;
datatype2 member2;
.
.
.
datatypen membern;
};
Example:
union item
{
int m;
float x;
char c;
}code;
Program on unions
#include<stdio.h>
#include<conio.h>
typedef union
{
int a;
float b;
char c;
} utype;
void main()
{
utype u1={10};
clrscr();
printf("\n u1.a is %d\n",u1.a);
u1.b=3.14;
printf("\n u1.b is %f\n",u1.b);
u1.c='a';
printf("\n u1.c is %c\n",u1.c);
printf("\n The size of union u1 is %d",sizeof(u1));
getch();
}
Size of Unions:
The size of union is the size of the highest memory required among all its members.
In the above example code, the size of union is 4 bytes as float is the highest
memory required member among all the union members. This can be obtained by
the size of operator.
sizeof(code);
or sizeof(union tag_name);
Example:
typedef int integer;
int x;
integer y;
Both x and y are integers.
Bit-Fields:
A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length. A
word (16bits here) can therefore be divided into a no. of bit fields. The name and
size of bit fields are defined using a structure.
The general form of bit field definition is
struct tag_name
{
datatype name1: bit_length;
datatype name2: bit_length;
.....
.....
datatype nameN: bit_length;
};
The datatype can be either int or unsigned int and the bit_length is the no. of
bits used for the specified name.
int or signed int must have bit_length atleast 2. One bit is dedicated for sign.
Field name is followed by the colon.
The bit_length is decided by range of value to be stored.
The largest value that can be stored is 2 n-1 , where n is bit_length. We have to
assign values within the bitfield’s range, else it gives unpredicated behaviour.
He first field always starts with the firt bit of the word.
A bit field cannot cross the integer storage boundary. That means the sum of
bit_lengths of all the bit fields cannot exceed 16.
There can be unnamed fields used for padding
There can be unused bits in a word.
We cannot obtain address of a bit field.
So, we cannot use scanf to read values to bit fields.
We cannot refer pointers to bit fields.
Bitfields cannot be arryed.
Example:
Struct personal
{
unsigned gender : 1
unsigned age : 7
unsigned m_status : 1
unsigned children : 3
unsigned : 4
} emp;
Once bit fields are defined, they can be accessed just like other structure members.
Example:
[Link]=1;
[Link]=30;
emp.m_status=0;
[Link]=0;
Its valid to combine normal structure members with bit field elements.
For example:
struct emp_info
{
int id;
char name[20];
unsigned age : 7;
unsigned gender : 1;
float sal;
};
Enumerated Datatype:
Enumerated datatype is a user –defined datatype in which enum keyword is
treated as type and used to declare variables that can have one of its enumeration
constants.
Syntax:
enum tag_name
{
val1;
val2;
.
.
valn;
};
Here Mon is assigned a value 3 and then remaining constants are assigned values
which increase by 1 successively.
In the enumerated type definition, if the enumeration constants are not assigned
any integers, then they will be automatically assigned a value which is +1 to the
value assigned to the previous enumeration constant and if the initial constant are
not assigned anything, then 0 is assigned.
Arrays Structures
1. An array is a collection of 1. Structure can have elements of
related data elements of same different types
type.
2. An array is a derived data 2. A structure is a programmer-
type defined or user-defined data type
3. Any array behaves like a 3. But in the case of structure,
built-in data types. All we have first we have to design(definition)
to do is to declare an array and declare a data structure
variable and use it. before the variable of that type
are declared and used.
Array elements are -. Structure elements are
homogeneous heterogeneous
Array allocates static memory Structures allocate dynamic
and uses index / subscript for memory and uses (.) operator for
accessing elements of the accessing the member of a
array. structure.
Array is a pointer to the first Structure is not a pointer
element of it
Array elements takes less time Structure members takes more
to access. time to access in comparison
with arrays.
FILE HANDLING
File Handling: Input and Output – Concept of a file, text files and binary files,
Formatted I/O, File I/O operations, Example Programs
Introduction to Files
Most programs have Input or output or both the operations. They are performed
using devices like keyboard, printer, monitor, etc attached to computer. To perform
I/O in a device independent form, C treats each of them in the same way, as a file.
Thus file can be read or written repeatedly from a permanent storage like
disk file or a stream of bytes received from or sent to a peripheral device
(keyboard, monitor, etc). The first one is called disk file. The second model of file
is called a device file or interactive file as it deals with device and user interactions.
Types of Files
Depending on the contents of the files, they are categorized as text files and
binary files. Text files require text streams and binary files require binary
streams as discussed above.
Depending on the file data accessing, they are categorized into two types.
Sequential access file
Random access file
Sequential access file: We can access data sequentially only. Data can be
accessed only if the data before it is accessed.
Operations on Streams(Files)
FILE is a type which deals with file streams. The operations on files can be
categorized into three major types.
Opening
Reading/Writing
Closing
Opening a stream(file)
To perform any operation on a file, it must be first opened. The file can be
opened by using the function fopen.
FILE *fp=fopen(“[Link]”,”r”);
FILE *fp;
fp=fopen(“c:\fed\[Link]”,”w”);
A text file abc is (.txt is extension in [Link]) opened in read
mode.
Various modes for opening a file and their purpose are specified below.
Mode Description
Closing a stream:
An open stream can be closed by using function fclose. The fclose is also declared
in stdio.h
fclose(FILE *stream);
Example: fclose(fp);
flcoseall();
fcloseall closes all the open streams and the corresponding files.
fcloseall doesn’t close standard streams.
#include<stdio.h>
main()
{
FILE *fp;
fp = fopen("[Link]", "w");//if file does not exist file will be
created
if (fp == NULL)
{
printf("File does not exist,please check!\n");
}
fclose(fp);
}
Character I/O
Line I/O
Block I/O
Character I/O
Character Input:
The fgetc and getc functions read a character from the input file referenced by fp
in argument. The return value is the character read, or in case of any error it
returns EOF. After reading a character, the file stream automatically moves to the
next character in the file. Both these functions are defined in stdio.h.
Syntax:
ch=fgetc(fp); ch=getc(fp);
Character Output:
The fputc and putc are functions to write a character to the file referenced by fp.
These functions takes two parameters, first one the character to be read and
second the fp. Both these functions are defined in stdio.h.
Syntax:
putc(ch,fp); putc(ch,fp);
#include<stdio.h>
main()
{
FILE *f1;
printf(“Data input output”);
f1=fopen(“[Link]”,”w”); /*Open the file Input in write mode*/
while((c=getchar())!=EOF) /*get a character from key board*/
fputc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“nData outputn”);
f1=fopen(“[Link]”,”r”); /*Reopen the file input*/
while((c=fgetc(f1))!=EOF) /*EOF-END OF FILE*/
printf(“%c”,c);
fclose(f1);
}
Formatted I/O
The fprintf and fscanf functions are identical to printf and scanf functions except
that they work on files. The first argument of theses 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 Is 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:
fscanf(f2,”%s%d”,item,&quantity”);
Like scanf, fscanf also returns the number of items that are successfully read.
The file position of a stream describes where in the file the stream is currently
reading or writing. I/O on the stream advances the file position through the file.
The file position is represented as a long integer, which counts the number of
bytes from the beginning of the file.
The initial value of file position indicator depends upon the mode in which the
file is opened. If the file is opened in read/write mode, the file position
indicator is at the beginning of the file and will have value zero. If the file is
opened in append mode, the initial value of the file position indicator is at
last.
As calls are made to read or write to a file, file position indicator is moved.
The current location of the file position indicator for the stream can be
determined by using the functions ftell and fgetpos.
Function ftell() returns the current position of the file pointer in a stream. The return
value is 0 or a positive integer indicating the byte offset from the beginning of an
open file. A return value of -1L indicates an error. Prototype of this function is as
shown below:
Function fgetpos() gets the current value of the file position indicator for the stream
in first argument and stores in second argument.
fseek()
This function positions the next I/O operation on an open stream to a new position
relative to the current position.
Here fp is the file pointer of the stream on which I/O operations are carried
on, offset is the number of bytes to move. The offset can be positive or negative,
positive when moving forward and negative for backward movement in the
file. Origin is the position in the stream to which the offset is applied, this can be
one of the following constants:
Example
The following example shows the usage of feof() function.
#include <stdio.h>
int main ()
{
FILE *fp;
char c;
fp = fopen("[Link]","r");
if(ferror(fp))
{
printf("Error in opening file");
return(-1);
}
while( !feof(fp))
{
c = fgetc(fp);
printf("%c", c);
}
fclose(fp);
return(0);
}
The C language provides a method to pass parameters to the main() function. This
is typically accomplished by specifying arguments on the operating system
command line (console).
The prototype for main() looks like:
void main(int argc, char *argv[])
{
…
}
There are two parameters passed to main(). The first parameter is the number of
items on the command line (int argc). Each argument on the command line is
separated by one or more spaces, and the operating system places each argument
directly into its own null-terminated string. The second parameter passed to main()
is an array of pointers to the character strings containing each argument (char
*argv[]).
For example, at the command prompt:
test_prog 1 apple orange 4096.0
There are 5 items on the command line, so the operating system will set argc=5 .
The parameter argv is a pointer to an array of pointers to strings of characters, such
that:
argv[0] is a pointer to the string “test_prog”
argv[1] is a pointer to the string “1”
argv[2] is a pointer to the string “apple”
argv[3] is a pointer to the string “orange”
argv[4] is a pointer to the string “4096.0”
and argc is 5
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2;
char ch, *fsrc,*fdest;
clrscr();
printf("Enter the file name to be copied\n");
gets(fsrc);
printf("Enter the file name to paste the copied contents.\n");
gets(fdest);
fp1=fopen(fsrc,"r");
fp2=fopen(fdest,"w");
if(ferror(fp1))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,fp2);
}
fcloseall();
fp2=fopen(fdest,"r");
printf("\nThe contents copied from the given file are ...\n");
while(!feof(fp2))
{
ch=getc(fp2);
putc(ch,stdout);
}
fclose(fp2);
getch();
}
OUTPUT:
Enter the file name to be read copied
[Link]
Enter the file name to paste the copied contents.
[Link]
The contents copied from the given file are ...
Hello
Hi
This is file handling program coping contents from one file to another.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch, *fname;
int nc,nl,nw;
nc=nl=nw=0;
clrscr();
printf("Enter the file name\n");
gets(fname);
fp=fopen(fname,"r");
if(ferror(fp))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
printf("\nThe contents of the given file are ...\n");
while(!feof(fp))
{
ch=getc(fp);
putc(ch,stdout);
nc++;
if(ch==' ' || ch=='\n')
nw++;
if(ch=='\n')
nl++;
}
printf("\nThe number of characters in the file are :%d\n",nc);
printf("\nThe number of words in the file are :%d\n",nw);
printf("\nThe number of lines in the file are :%d\n",nl);
fcloseall();
getch();
}
OUTPUT:
Enter the file name
[Link]
The contents of the given file are ...
Hello
Hi
This is file handling program coping contents from one file to another.
The number of characters in the file are :63
The number of words in the file are :14
The number of lines in the file are : 3
Write a C program to merge two files into a third file. The names of the
files must be entered using command line arguments.
#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[])
{
FILE *fp1,*fp2;
char ch;
clrscr();
if(argc!=4)
{
printf("\nNot enough arguments are passed. Program halted!!");
getch();
exit(0);
}
fp1=fopen(argv[1],"r");
fp2=fopen(argv[3],"w");
if(ferror(fp1))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
printf("\nThe contents of the given file1 are ...\n");
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,stdout);
putc(ch,fp2);
}
fclose(fp1);
fp1=fopen(argv[2],"r");
if(ferror(fp1))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
printf("\nThe contents of the given file2 are ...\n");
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,stdout);
putc(ch,fp2);
}
fcloseall();
fp1=fopen(argv[3],"r");
if(ferror(fp1))
{
printf("\nError occured while during file opening. Program
halted!!");
exit(0);
}
printf("\nThe contents of the file3 merged from file1 and file2 are ...\n");
while(!feof(fp1))
{
ch=getc(fp1);
putc(ch,stdout);
}
fclose(fp1);
getch();
}
OUTPUT:
The contents of the given file1 are ...
Hello
Hi
This is file handling program merging contents of two files to another.
The contents of the file3 merged from file1 and file2 are ...
Hello
Hi
This is file handling program merging contents of two files to another.
Using command line arguments, file names passed as arguments.