Hello, firstly I am new here and if this question is posted in a wrong way, please do suggest me to modify it as per the needs of the community here.
Anyway, I am trying to print the string length of the first argument that is passed to main. Here is the code.
Code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<error.h>
int main(int argc, char* argv[])
{
FILE* fp;
fp=stdin;
char* filename=stdin;
char* searchString=NULL;
if(argc>1)
{
int i=1;
for(i=1;i<argc;i++)
{
switch(i)
{
case 1:
searchString=(char*)malloc((int)(strlen(argv[i]))*sizeof(char));
memcpy(searchString,argv[i],strlen(argv[i]));
break;
case 2:
filename=(char*)malloc((int)strlen(argv[i])*sizeof(char));
strcpy(filename,argv[i]);
fp=fopen(argv[i],"r");
if(fp==NULL)
{
exit(EXIT_FAILURE);
}
break;
default:
break;
}
}
}
else
{
printf("Usage: fgrep [OPTION]... PATTERN [FILE]...\n");
printf("Try './mygrep --help' for more information.\n");//need to implement this yet
}
printf("%d\n",strlen(searchString));
return 0;
}
In linux terminal, after compiling when I run the command,
./nameofProgram abcdefghijk filename.txt, I am getting the correct output i.e., 11 as my string length of the string "abcdefghijk", but when I input the string as "abcdefghijkl", i get the output as 13 instead of 12. So how do I solve it?
Thanks