Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

Unix tail program in C using an implemented function

I have implemented my own dynamic-memory version of getline function:

char * fgetline(FILE * f)

Starts with 30 character buffer and when the buffer is full allocate a new one copy the contents and free the old buffer. When we get EOF or we return from the function.

I want to use this function to implement a version of the program tail. Input comes from stdin, output goes to stdout. If the ?rst argument begins with -, everything after the - is the number of lines to print. The default number of lines to print is 10, when no argument is given.

I have thought until now that I should use the function:

int atoi (const char *s) 

from stdlib.h and have an array of pointers to lines but I don't know exactly how to do this.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Declare your main function as

 int main (int argc, char**argv) {
 }

If you compile your program to myprog executable, and invoke it as myprog -20 somefile anotherfile then you have:

argc == 4 
&& strcmp(argv[0], "myprog") == 0
&& strcmp(argv[1], "-20") == 0
&& strcmp(argv[2], "somefile") == 0
&& strcmp(argv[3], "anotherfile") == 0
&& argv[4] == NULL

in other words, you might want to have your program containing

int nblines = 10;

int main(int argc, char**argv) {
  int argix = 1;
  if (argc>1) {
    if (argv[1][0]=='-') 
      { 
         nblines = atoi(argv[1]+1);
         argix = 2;
      }
     for (; argix < argc; argix++)
        tail (argv[argix]);
  }
  return 0;
}

It is up to you to implement your void tail(char*filename); function appropriately. Don't forget to compile with all warnings & debugging info, e.g. with gcc -Wall -g on Linux. Use your debugger (gdb on Linux) to debug your program. Take into account that fopen can fail, and use errno to display an appropriate error message.

Notice that you don't need your fgetline function. The getline(3) function is standard (in Posix 2008) and is dynamically allocating the line buffer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...