Implementing ‘strcat( )’ 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 ‘strcat(s1,s2)’:

strcat( s1, s2) is a standard library function which appends the string s2 with s1 provided s1 must be large enough to hold s2.

Example:

We are taking the input from the user using command linearguments.
input = ./a.out Subhash programming
output = Subhashprogramming

In the given example “Subhash” is the target string and “programming “is the source string . So argv[1] = “Subhash ” and argv[2] = “programming”.The strcat( ) concatenates the argv[2] with argv[1] . Therefore in this case the output string is “Subhashprogramming”.

 

Logic:

1. Take s1 and s2 strings using command line arguments.
2. Call the function my_strcat( ) and pass the base address of the argv[1] and argv[2].( my_strcat(argv[1], argv[2]) .
3. The control goes to the function defination( void my_strcat(char * p, char * q)).
4. Increment the pointer ‘p’ until it reaches ‘\0’ character (while(*p != ‘\0’)).
5. If the above condition is true then come out of the loop and start appending the characters from q to p(while(*p++ = *q++)).
6. The condition specified in 5 fails when ‘\0’ character is copied into the s1.
7.Come out of the loop and print the string s1.

 

Source code:

#include<stdio.h>
void my_strcat(char *,char *);
int main(int argc, char*argv[])
{
             my_strcat(argv[1] , argv[2]);
             printf("%s",argv[1]);
}
void my_strcat(char *p,char *q)
{
             while(*p != '\0')
              p++;
              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.