Structure, Union and File Management in C - 250324 - 091204
Structure, Union and File Management in C - 250324 - 091204
1. Define a structure? Write the syntax for structure declaration with an example.
Ans:
The structure definition associated with the structure name is referred as tagged structure. It
doesn’t create an instance of a structure and does not allocate any memory.
{ {
…… float marks[6];
…… };
Type variable-n;
};
Where,
- struct is the keyword which tells the compiler that a structure is being defined.
- Tag name is the name of the structure.
- variable1, variable2 … are called members of the structure.
- The members are declared within curly braces.
- The closing brace must end with the semicolon.
(ii) Type-defined structures:-
- The structure definition associated with the keyword typedef is called type-defined
structure.
{ {
…… float marks[6];
…… }student;
Type variable-n;
}Type;
where
Memory is not reserved for the structure definition since no variables are associated with the
structure definition. The members of the structure do not occupy any memory until they are
associated with the structure variables.
Type v1,v2,v3,….vn;
Alternate way:
struct TAG
{
Type varaible1;
Type variable2;
……
……
Type variable-n;
Ex:
struct book
char name[30];
int pages;
float price;
}b1,b2,b3;
(ii) Each course is associated with course name (String), duration, number of students.
(A College can offer 1 to 50 such courses)
Ans:
struct college
char code[2];
char college_name[20];
int year;
int no_of_courses;
};
Variable declaration for structure college :-
void main( )
….
struct course
char course_name[20];
float duration;
int no_of_students;
};
void main( )
….
struct student
int roll_number;
float avg;
Consider the structure definition for student with three fields name, roll number and average
marks. The initialization of variable can be done as shown below,
typedef struct
int x;
int y;
float t;
char u;
} SAMPLE;
4. Define a structure type personal, that would contain person name, date of joining and
salary. Write a program to initialize one person data and display the same.
Ans:
struct personal
char name[20];
int day;
char month[10];
int year;
float salary;
};
void main( )
printf(“%s%d%s%d%f”,person.name,person.day,person.month,person.year,person.salary );
5. How to access the data for structure variables using member operator(„.‟)?Explain
with an example.
Ans:
We know that variables can be accessed and manipulated using expressions and operators.
On the similar lines, the structure members can be accessed and manipulated. The members
of a structure can be accessed by using dot(.) operator.
structure_variable_name . structure_member_name
struct student
int roll_number;
float avg;
};
6. Define a structure type book, that would contain book name, author, pages and price.
Write a program to read this data using member operator („.‟) and display the same.
Ans:
struct book
char name[20];
int day;
char month[10];
int year;
float salary;
};
void main( )
Output:-
KAMTHANE
609
350.00
This method is to pass each member of the structure as an actual argument of the function
call. The actual arguments are treated independently like ordinary variables. This is the most
elementary method and becomes unmanageable and inefficient when the structure size is
large.
Program:
#include<stdio.h>
main ( )
{
float arriers (char *s, int n, float m);
typedef struct emp
{
char name[15];
int emp_no;
float salary;
}record;
record e1 = {"smith",2,20000.25};
e1.salary = arriers(e1.name,e1.emp_no,e1.salary);
}
float arriers(char *s, int n, float m)
{
m = m + 2000;
printf("\n%s %d %f ",s, n, m);
return m;
}
Output
smith 2 22000.250000
Ans:
Structures are more useful if we are able to pass them to functions and return them.
This method involves passing a copy of the entire structure to the called function. Any
changes to structure members within the function are not reflected in the original structure. It
is therefore, necessary for the function to return the entire structure back to the calling
function.
The general format of sending a copy of a structure to the called function is:
data_type function_name(struct_typetag_name)
………
………
return(expression);
}
The called function must be declared for its type, appropriate to the data type it is expected to
return.
The structure variable used as the actual argument and the corresponding formal argument in
the called function must be of the same struct type.
The return statement is necessary only when the function is returning some data back to the
calling function. The expression may be any simple variable or structure variable or an
expression using simple variables.
When a function returns a structure, it must be assigned to a structure of identical type in the
calling function. The called functions must be declared in the calling function appropriately.
Program:
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[20];
float percentage;
};
int main()
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
return 0;
{
printf(" Id is: %d \n", record.id);
Output:
Id is: 1
Output:
Smith 2 20000.25
Jones 16 9999.99
10. What is an array of structure? Declare a variable as array of structure and initialize
it? (or)When the array of structures is used? Write syntax for array of structure.
Ans:
An array is a collection of elements of same data type that are stored in contiguous memory
locations. A structure is a collection of members of different data types stored in contiguous
memory locations. An array of structures is an array in which each element is a structure.
This concept is very helpful in representing multiple records of a file, where each record is a
collection of dissimilar data items.
As we have an array of integers, we can have an array of structures also. For example,
suppose we want to store the information of class of students, consisting of name,
roll_number and marks, A better approach would be to use an array of structures.
Let‟s take an example, to store the information of 3 students, we can have the following
structure definition and declaration,
struct student
{
char name[10];
int rno;
float avg;
};
struct student s[3];
Defines an array called s, which contains three elements. Each element is defined to be of
type struct student.
Let‟s take an example, to store the information of 5 employees, we can have the following
structure definition and declaration,
struct employee
{
int empid;
char name[10];
float salary;
};
struct employee emp[5];
Defines array called emp, which contains five elements. Each element is defined to be of type
struct employee.
#include<stdio.h>
struct student
char rollno[10];
char name[20];
float sub[3];
float total;
};
void main( )
int i, j, total = 0;
gets(s[i].name);
total=0;
scanf("%d",&s[i].sub[j]);
printf("\n******************************************");
printf("\n******************************************");
12. Write a C program using array of structure to create employee records with the
following fields: emp-id, name, designation, address, salary and display it.
Ans:
#include<stdio.h>
struct employee
{
int emp_id;
char name[20];
char designation[10];
char address[20];
float salary;
}emp[3];
void main( )
int i;
scanf(“%d”,&emp[i].emp_id);
gets(emp[i].name);
gets(emp[i].designation);
gets(emp[i].address);
scanf(“%f”,&emp[i].salary);
printf("\n******************************************");
printf("\n******************************************");
printf(“%d”,emp[i].emp_id);
puts(emp[i].name);
puts(emp[i].designation);
puts(emp[i].address);
printf(“%f”,emp[i].salary);
Ans:
A structure which includes another structure is called nested structure or structure within
structure. i.e a structure can be used as a member of another structure. There are two methods
for declaration of nested structures.
struct tag_name1
type1 member1;
…….
…….
};
struct tag_name2
type1 member1;
……
……
……
};
outer_structure_variable . inner_structure_variable.member_name
(ii) The syntax of another method for the nesting of the structure is as follows
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
Example :
struct stud_Res
{
int rno;
char nm[50];
char std[10];
struct stud_subj
{
char subjnm[30];
int marks;
}subj;
}result;
In above example, the structure stud_Res consists of stud_subj which itself is a structure with
two members. Structure stud_Res is called as 'outer structure' while stud_subj is called as
'inner structure.'
The members which are inside the inner structure can be accessed as follow :
result.subj.subjnm
result.subj.marks
Program to demonstrate nested structures.
#include <stdio.h>
#include <conio.h>
struct stud_Res
{
int rno;
char std[10];
struct stud_Marks
{
char subj_nm[30];
int subj_mark;
}marks;
}result;
void main()
{
printf("\n\t Enter Roll Number : ");
scanf("%d",&result.rno);
printf("\n\t Enter Standard : ");
scanf("%s",result.std);
printf("\n\t Enter Subject Code : ");
scanf("%s",result.marks.subj_nm);
printf("\n\t Enter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("\n\n\t Roll Number : %d",result.rno);
printf("\n\n\t Standard : %s",result.std);
printf("\nSubject Code : %s",result.marks.subj_nm);
printf("\n\n\t Marks : %d",result.marks.subj_mark);
}
Output:
Enter roll number : 1
Enter standard :Btech
Enter subject code : GR11002
Enter marks : 63
Roll number :1
Standard :Btech
Subject code : GR11002
Marks : 63
14. Write a C program using nested structures to read 3 employees details with the
following fields; emp-id, name, designation, address, da ,hra and calculate gross
salary of each employee.
Ans:
#include<stdio.h>
struct employee
{
int emp_id;
char name[20];
char designation[10];
char address[20];
struct salary
float da;
float hra;
}sal;
}emp[3];
void main( )
int i;
grosssalary = 0;
scanf(“%d”,&emp[i].emp_id);
gets(emp[i].name);
gets(emp[i].designation);
gets(emp[i].address);
scanf(“%f”,&emp[i].sal.da);
scanf(“%f”,&emp[i].sal.hra);
printf("\n******************************************");
printf(“%d”,emp[i].emp_id);
puts(emp[i].name);
puts(emp[i].designation);
puts(emp[i].address);
printf(“%f”,emp[i].sal.da);
printf(“%f”,emp[i].sal.hra);
printf(“%f”,grosssalary);
15. Distinguish between Arrays within Structures and Array of Structure with examples.
Ans:
struct student
int roll_number;
float avg;
};
s1.marks [1] --> will refer the 1st element in the marks
s1.marks [2] --> will refer the 2ndt element in the marks
Array of structure
An array is a collection of elements of same data type that are stored in contiguous memory
locations. A structure is a collection of members of different data types stored in contiguous
memory locations. An array of structures is an array in which each element is a structure.
This concept is very helpful in representing multiple records of a file, where each record is a
collection of dissimilar data items.
Ex:
Let‟s take an example, to store the information of 5 employees, we can have the following
structure definition and declaration,
struct employee
{
int empid;
char name[10];
float salary;
};
struct employee emp[5];
Defines array called emp, which contains five elements. Each element is defined to be of type
struct student.
For the student details, array of structures can be initialized as follows,
struct employee emp[5] = {{1,”ramu”25,20000},
{2,”ravi”,65000},
{3,”tarun”,82000},
{4,”rupa”,5000},
{5,”deepa”,27000}};
16. Write a C program using structure to create a library catalogue with the following
fields: Access number, author‟s name, Title of the book, year of publication,
publisher‟s name, and price.
Ans:
struct library
{ int acc_no;
char author[20];
char title[10];
int year_pub;
char name_pub[20];
float price;
};
void main( )
We have pointers pointing to int, float, arrays etc., We also have pointers pointing to
structures. They are called as structure pointers.
Syntax:
struct tagname
{
datatype member1;
datatype member2;
};
ptr=*var;
(*ptr).member1; or ptr->member1;
The parentheses around *ptr are necessary because the member operator ‟.‟ has a higher
precedence than the operator „*‟
Example:
struct student
int rno;
char name[20];
};
ptr=&s1;
to access
(*ptr).rno;
(*ptr).name;
(or)
ptr->rno;
ptr->name;
Program to read and display student details using pointers to structures
struct student
int HTNO;
char NAME[20];
float AVG;
};
void main()
ptr=&s1;
scanf(“%d%s%f”,&ptr->HTNO,ptr->NAME,&ptr->AVG);
printf(“HTNO=%d”,ptr->HTNO);
printf(“NAME=%s”,ptr->NAME);
printf(“AVERAGE MARKS=%f”,ptr->AVG);
Self-referential structure
A structure definition which includes at least one member as a pointer to the same structure is
known as self-referential structure.
It can be linked together to form useful data structures such as lists, queues, stacks and trees.
struct tag_name
{
Type1 member1;
Type2 member2;
……….
};
Ex:-
struct node
int data;
} n1, n2;
A union is one of the derived data types. Union is a collection of variables referred under a
single name. The syntax, declaration and use of union is similar to the structure but its
functionality is different.
Syntax:
union union_name
<data-type> element 1;
<data-type> element 2;
………………
}union_variable;
Example:
union techno
int comp_id;
char nm;
float sal;
}tch;
A union definition and variable declaration can be done by using any one of the following
We can access various members of the union as mentioned: a.c a.i a.f
A union creates a storage location that can be used by any one of its members at a time.
When a different member is assigned a new value, the new value supersedes the previous
members‟ value.
Structure Union
(i) Keyword Struct Union
(vii) Size Size of the structure depends Size is given by the size of the
on the type of members, adding largest member
size of all the members. sizeof(un_variable)
sizeof (st_var);
20. Define file and explain about the types of files with examples.
Ans :
A file is an external collection of related data treated as a unit. A file is a place on a
disk where a group of related data is stored and retrieved whenever necessary without
destroying data
The primary purpose of a file is to keep record of data. Record is a group of related
fields. Field is a group of characters which convey meaning.
Files are stored in auxiliary or secondary storage devices. The two common forms of
secondary storage are disks (hard disk, CD and DVD) and tapes.
Each file ends with an end of file (EOF) at a specified byte number, recorded in file
structure.
A file must first be opened properly before it can be accessed for reading or writing.
When a file is opened an object (buffer) is created and a stream is associated with the
object.
The read mode (r) opens an existing file for reading. When a file is opened in this mode, the
file marker or pointer is positioned at the beginning of the file (first character).The file must
already exist: if it does not exist a NULL is returned as an error. If we try to write a file
opened in read mode, an error occurs.
The write mode (w) opens a file for writing. If the file doesn‟t exist, it is created. If it already
exists, it is opened and all its data is erased; the file pointer is positioned at the beginning of
the file It gives an error if we try to read from a file opened in write mode.
The append mode (a) opens an existing file for writing instead of creating a new file.
However, the writing starts after the last character in the existing file ,that is new data is
added, or appended, at the end of the file. If the file doesn‟t exist, new file is created and
opened. In this case, the writing will start at the beginning of the file.
In this mode file is opened for both reading and writing the data. If a file does not exist then
NULL, is returned.
Syntax: fp=fopen (“filename”,”r+”);
In this mode file is opened for both writing and reading the data. If a file already exists its
contents are erased and if a file does not exist then a new file is created.
In this mode file is opened for reading the data as well as data can be added at the end.
NOTE:To perform operations on binary files the following modes are applicable with an
extension b like rb,wb,ab,r+b,w+b,a+b,which has the same menaing but allows to perform
operations on binary files.
23. What are the file I/O functions in C. Give a brief note about the task performed by
each function.
Ans:
In order to perform the file operations in C we must use the high level I/O functions which
are in C standard I/O library. They are
i) getc() and putc() functions:
getc()/fgetc() : It is used to read a character from a file that has been opened in a read mode.
It reads a character from the file whose file pointer is fp. The file pointer moves by one
character for every operation of getc(). The getc() will return an end-of –marker EOF, when
an end of file has been reached.
Syntax: getc(fp);
Ex: char ch;
ch=getc(fp);
putc()/fputc() -:It is used to write a character contained in the character variable to the
file associated with the FILE pointer fp. fputc() also returns an end-of –marker EOF, when an
end of file has been reached.
Syntax: putc(c,fp);
Example: char c;
putc(c,fp);
Program using fgetc() and fputc():
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("input1.txt","w");
printf("\n enter some text hereand press cntrl D or Z to stop :\n");
while((ch=getchar())!=EOF)
fputc(ch,fp);
fclose(fp);
fp=fopen("input1.txt","r");
printf("\n The entered text is : \n");
while((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
ii) fprintf() and fscanf():
In order to handle a group of mixed data simultaneously there are two functions that are
fprintf() and fscanf().These two 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.
fprintf(): The general form of fprintf() is
Syntax: fprintf(fp,”control string”,list);
where fp is a file pointer associated with a file that has been opened for writing . The control
string contains output specifications for the items in the list. .
Example: fprintf(fp,”%s%d”,name,age);
fscanf() : It is used to read a number of values from a file.
Syntax: fscanf(fp,”control string”,list);
Example: fscanf(fp2,”%s %d”,item,&quantity);
like scanf , fscanf also returns the number of items that are successfully read. when the end of
file is reached it returns the value EOF.
Program using fscanf() and fprintf():
#include<stdio.h>
void main()
{
int a=22,b;
char s1[20]="Welocme_to_c",s2[20];
float c=12.34,d;
FILE *f3;
f3=fopen("mynew3","w");
fprintf(f3,"%d %s %f",a,s1,c);
fclose(f3);
f3=fopen("mynew3","r");
fscanf(f3,"%d %s %f",&b,s2,&d);
printf("\n a=%d \t s1=%s \t c=%f \n b=%d \t s2=%s \t d=%f",a,s1,c,b,s2,d);
fclose(f3);
}
iii) getw() and putw():
The getw() and putw()are integer oriented functions .They are similar to the getc() and putc()
functions and are used to read and write integer values . These functions would be useful
when we deal with only integer data. The general form of getw() and putw() are
Syntax: putw(integer,fp);
Syntax: getw(fp);
Program using getw() and putw():
/*Printing odd numbers in odd file and even numbers in even file*/
#include<stdio.h>
void main()
{
int x,i;
FILE *f1,*fo,*fe;//creating a file pointer
f1=fopen("anil.txt","w"); //opening a file
printf("\n enter some numbers into file or -1 to stop \n");
for(i=0;i<20;i++)
{
scanf("%d",&x);
if(x== -1)break;
putw(x,f1); //writing read number into anil.txt file one at a time
}
fclose(f1); //closing a file opened for writing input
printf("\n OUTPUT DATA\n");
f1=fopen("anil.txt","r");//open anil in read mode to read data
fo=fopen("odd3f","w");
fe=fopen("even3f","w");
while((x=getw(f1))!=EOF)
{
printf("%d\t",x);
if(x%2==0)
putw(x,fe);
else
putw(x,fo);
}
fcloseall();
fo=fopen("odd3f","r");
printf("\n contents of odd file are :\n");
while((x=getw(fo) )!= EOF)
printf(" %d\t",x);
fe=fopen("even3f","r");
printf("\n contents of even file are :\n");
while((x=getw(fe)) != EOF)
printf(" %d\t",x);
fcloseall();
}
iv) fputs() and fgets():
fgets(): It is used to read a string from a file pointed by file pointer. It copies the string to a
memory location referred by an array.
Syntax: fgets(string,length,filepointer);
Example: fgets(text,50,fp1);
fputs(): It is used to write a string to an opened file pointed by file pointer.
Syntax: fputs(string,filepointer);
Example: fputs(text,fp);
Program using fgets() and fputs():
#include<stdio.h>
void main()
{
FILE *fp;
char str[50];
fp=fopen("fputget.txt","r");
printf("\n the read string is :\n");
fgets(str,50,fp);
puts(str);
fclose(fp);
fp=fopen("fputget.txt","a+");
printf("\n Enter string : \n");
gets(str);
fputs(str,fp);
puts(str);
fclose(fp);
}
Block or structures read and write:
Large amount of integers or float data require large space on disk in text mode and turns out
to be inefficient .For this we prefer binary mode and the functions used are
v) fread() and fwrite():
fwrite(): It is used for writing an entire structure block to a given file in binary mode.
Syntax: fwrite(&structure variable,sizeof(structure variable),1,filepointer);
Example: fwrite(&stud,sizeof(stud),1,fp);
fread(): It is used for reading an entire structure block from a given file in binary mode.
Syntax: fread(&structure variable,sizeof(structure variable),1,filepointer);
Example: fread(&emp,sizeof(emp),1,fp1);
Program using fread() and fwrite():
#include<stdio.h>
struct player
{
char pname[30];
int age;
int runs;
};
void main()
{
struct player p1,p2;
FILE *f3;
f3=fopen("player.txt","w");
printf("\n Enter details of player name ,age and runs scored :\n ");
fflush(stdin);
scanf("%s %d %d",p1.pname,&p1.age,&p1.runs);
fwrite(&p1,sizeof(p1),1,f3);
fclose(f3);
f3=fopen("player.txt","r");
fread(&p2,sizeof(p2),1,f3);
fflush(stdout);
printf("\nPLAYERNAME:=%s\tAGE:=%d\tRUNS:=%d ",p2.pname,p2.age,p2.runs);
fclose(f3);
}
fseek:-
fseek function is used to move the file pointer to a desired location within the file.
Syntax: fseek(file ptr,offset,position);
file pointer is a pointer to the file concerned, offset is a number or variable of type long and
position is an integer number which takes one of the following values. The offset specifies
the number of positions(Bytes) to be moved from the location specified by the position
which can be positive implies moving forward and negative implies moving backwards.
POSITION VALUE VALUE CONSTANT MEANING
0 SEEK_SET BEGINNING OF FILE
1 SEEK_CUR CURRENT POSITION
2 SEEK_END END OF FILE
Example: fseek(fp,10,0) ;
fseek(fp,10,SEEK_SET);// file pointer is repositioned in the forward direction 10 bytes.
fseek(fp,-10,SEEK_END); // reads from backward direction from the end of file.
When the operation is successful fseek returns 0 and when we attempt to move a file
beyond boundaries fseek returns -1.
Some of the Operations of fseek function are as follows:
STATEMENT MEANING
fseek(fp,0L,0); Go to beginning similar to rewind()
fseek(fp,0L,1); Stay at current position
fseek(fp,0L,2); Go to the end of file, past the last character of the file.
fseek(fp,m,0); Move to (m+1)th byte in the file.
fseek(fp,m,1); Go forward by m bytes
fseek(fp,-m,1); Go backwards by m bytes from the current position
fseek(fp,-m,2); Go backwards by m bytes from the end.(positions the file to the m th
character from the end)
void main()
{
FILE *fp;
char ch;
fp=fopen("my1.txt","r");
if(fp==NULL)
printf(“\n file cannot be opened”);
while(!feof(fp))
{
ch=getc(fp);
if(ferror(fp))
perror(“problem in the file”);
else
putchar(ch);
}
fclose(fp);
}
f1 = fopen(“data.txt”,"r");
putchar(ch);
fclose(f1);
f2 = fopen(“dupmynew2.txt”,"r");
putchar(ch);
fclose(f2);
28. Write a c program to merge two files into a third file? (Or)
Write a c program for the following .there are two input files named “first.dat” and
“second.dat” .The files are to be merged. That is,copy the contents of first.dat and then
second.dat to a new file named result.dat?
Ans: Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20];
printf("Enter name of first file\n");
gets(file1);
printf("Enter name of second file\n");
gets(file2);
printf("Enter name of file which will store contents of two files\n");
gets(file3);
fs1=fopen(file1,"w");
printf("\n enter some text into file1 here and press cntrl D or Z to stop :\n");
while((ch=getchar())!=EOF)
fputc(ch,fs1);
fclose(fs1);
fs2=fopen(file2,"w");
printf("\n enter some text into file2 here and press cntrl D or Z to stop :\n");
while((ch=getchar())!=EOF)
fputc(ch,fs2);
fclose(fs2);
fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");
if( fs1 == NULL || fs2 == NULL )
{
perror("Error ");
exit(1);
}
ft = fopen(file3,"w");
while( ( ch = fgetc(fs1) ) != EOF )
fputc(ch,ft);
while( ( ch = fgetc(fs2) ) != EOF )
fputc(ch,ft);
printf("Two files were merged into %s file successfully.\n",file3);
fcloseall();
ft = fopen(file3,"r");
printf(“\n the merged file contents are :”);
while( ( ch = fgetc(fs1) ) != EOF )
putchar(ch);
fclose(ft);
return 0;
}
31. Explain the command line arguments. What are the syntactic constructs followed in
„C‟?
Ans :
Command line argument is the parameter supplied to a program when the program is
invoked. This parameter may represent a file name the program should process. For example,
if we want to execute a program to copy the contents of a file named X_FILE to another one
name Y_FILE then we may use a command line like
C:> program X_FILE Y_FILE
Program is the file name where the executable code of the program is stored. This
eliminates the need for the program to request the user to enter the file names during
execution. The „main‟ function can take two arguments called argc, argv and information
contained in the command line is passed on to the program to these arguments, when „main‟
is called up by the system.
The variable argv is an argument vector and represents an array of characters pointers that
point to the command line arguments.
The argc is an argument counter that counts the number of arguments on the command line.
The size of this array is equal to the value of argc. In order to access the command line
arguments, we must declare the „main‟ function and its parameters as follows:
main(argc,argv)
int argc;
char *argv[ ];
{
……….
}
Generally argv[0] represents the program name.
Example:- A program to copy the contents of one file into another using command line
arguments.
#include<stdio.h>
#include<stdlib.h>
void main(int argc,char* argv[]) /* command line arguments */
{
FILE *ft,*fs; /* file pointers declaration*/
int c=0;
if(argc!=3)
Printf(“\n insufficient arguments”);
fs=fopen(argv[1],”r”);
ft=fopen(argv[2],”w”);
if (fs==NULL)
{
printf(“\n source file opening error”);
exit(1) ;
}
if (ft==NULL)
{
printf(“\n target file opening error”);
exit(1) ;
}
while(!feof(fs))
{
fputc(fgetc(fs),ft);
c++;
}
printf(“\n bytes copied from %s file to %s file =%d”, argv[1], argv[2], c);
c=fcloseall(); /*closing all files*/
printf(“files closed=%d”,c);
}
32. Write a c program to add two numbers using command line arguments?
Ans:
Program:
#include<stdio.h>
int main(int argc, char *argv[])
{
int x, sum=0;
printf("\n Number of arguments are:%d", argc);
printf("\n The agruments are:");
for(x=0;x<argc; x++)
{
printf("\n agrv[%d]=%s", x, argv[x]);
if(x<2)
continue;
else
sum=sum+atoi(argv[x]);
}
printf("\n program name:%s",argv[0]);
printf("\n name is:%s",argv[1]);
printf("\n sum is:%d",sum);
return(0);
}