Unix tail program in C using an implemented function

时间秒杀一切 提交于 2019-12-25 18:53:45

问题


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 \n 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 first 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?


回答1:


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.



来源:https://stackoverflow.com/questions/13100211/unix-tail-program-in-c-using-an-implemented-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!