Trying to redirect file contents to display a specific line provided by command line arguements in C

54 views Asked by At

I am using gcc compiler.I have a file called lines.txt and i am trying to have the user enter an invocation like ./lines 4 < lines.txt to display only line number 4 of the text file. So far i have it so that if the user enters ./lines 4 lines.txt without the redirection, it displays the 4th line of the text file. I can't get it to work like this with redirection though. I also am using a makefile to compile and clean the code. This is my code so far:

#define BUFSIZE 1000

int main(int argc, char *argv[])
{

// argv[0] contains the file name
char *str1 = argv[0];       // storing the file name
char *str2 = "./lines";
int ret;


        if(strstr(buff, argv[1]) != NULL)
        {
            printf("%s", buff); /* ...such as show it on the screen */
        }

    }
    fclose(fp);  /* close the file */ 

    }
}

My current output without redirection is:

~/Desktop/project3 $ ./lines 4 lines.txt

First arg is: ./lines

Second arg is: 4

Third arg is: lines.txt

Read file name correctly. File contains:

Line 4

0

There are 0 answers