Search code examples
ctailargvargc

Build a tail program with argc and argv[]


The exercise requests a tail program with argc and argv[].It will have a specific number of lines.The user will put a N argument and than the program will print the last n lines.When I call this program from cmd as tail 3 program name the program opens but it doesnt print anything.Here is the code.

#include <stdio.h>
int main (int argc,char *argv[])
{
    char *linja[]={"Mjeshter Ciko", "Sisteme Elektronike" , "Bisha" , "Super Mario Bros" , "Pallim Gjoni"};
    int i=0;
    if (argc!=3)
    {
               printf("Your Request can't be completed\n");
               printf("The format is Tail X Program Name\n");
               return -1;
               }
    if(*argv[1] <= 4)
    {
                printf("The Last Lines Are: \n");
                for(i=4 ;*argv[1]>=0; i--,*argv[1]--)
                {
                        printf("%s\n",linja[i]);
                        }
                        }
                        return 0;
                        }

Solution

  • The expression *argv[1] <= 4 will be false. argv[1] is a string and *argv[1] is the first character of that string. You have to convert the textual representation of the number to a proper number.

    Try instead strtol(argv[1], NULL, 10) <= 4.