Implementing ‘strcpy( )’ using command line arguments

IMPLEMENTATION OF STANDARD STRING LIBRARY FUNCTIONS USING COMMAND LINE ARGUMENTS

Command line arguments:

In C language main() is the only function which can defined in multiple ways.It can recieve no arguments, two arguments or 3 arguments. Using these arguments the main function will recieve the arguments from the console.
The main function can be define in the following ways:
1. int main( )
2. int main( int argc, char *argv[ ])

argc:
It is called as argument count ,it tells the number of arguments that is being passed to the main function.

argv[ ]:
This is called as argument vector ,its an array whose each element would be pointing to the arguments that are passed to the main function.

Implementing ‘strcpy(s2,s1)’:

strcpy( s2, s1) is a standard library function which copies all the contents from the source s1 to target s2 including the null character (‘\0’) and the target string must be large enough to receive the copy.

Example:

We are taking the input  using command linearguments.

input = ./a.out Subhash programming
output = programming

In the given example “Subhash” is the target string and “programming “is the source string . So argv[1] = “Subhash ” and argv[2] = “programming”.The strcpy( ) copies the contents of argv[2] into the argv[1] . Therefore in this case the output string is “programming”.

 

Logic:

 

1.Take source and target strings using command line arguments.
2.Call the function my_strcpy( ) and pass the base address of the argv[1] and argv[2].( my_strcpy(argv[1]) .
3.The control goes to the function defination( void my_strcpy(char * p, char * q).
4.Copy each character of the value to which p is pointing (*p) into the corresponding character of the value to which q is pointing including the ‘\0’ character
( while(*p = *q)).
5.If the above codition is true increment both the pointers and continue the loop until the null character of the target string is enountered.
6. If the condition specified in 4 fails the control comes out of the loop and prints the resultant string.

 

Source code:

#include<stdio.h>
void my_strcpy(char *p,char*q);
int main(int argc,char* argv[])
{
          int i;
          my_strcpy(argv[1],argv[2] );
          printf("%s\n",argv[1]);
}
void my_strcpy(char *p,char*q)
{
            while(*p++ = *q++)
                   ;
}

This article is written by one of my student as part of their blog writing exercise.

To learn more programs on C and C++, click this link: Interview Questions

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.

VIEW SUBHASH’s PROFILE

SUBHASH LOVES TO TEACH ! CLICK HERE !

Subhash Embedded Classes is one of the Best Embedded Systems Training Institute in Bangalore

 

No Comment

You can post first response comment.

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.