使用已实现功能的C中的Unix尾部程序 [英] Unix tail program in C using an implemented function

查看:64
本文介绍了使用已实现功能的C中的Unix尾部程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了自己的getline函数的动态内存版本:

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

char * fgetline(FILE * f)

以30个字符的缓冲区开始,当缓冲区已满时,分配一个新的副本内容并释放旧的缓冲区.当我们得到 EOF \ n 时,我们从函数中返回.

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.

我想使用此功能来实现程序尾部的版本.输入来自标准输入,输出进入标准输出.如果第一个参数以-开头,则-之后的所有内容都是要打印的行数.如果未指定任何参数,则默认要打印的行数为10.

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) 

来自 stdlib.h ,并且具有指向行的指针数组,但我不知道该怎么做.

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

有什么想法吗?

推荐答案

将您的 main 函数声明为

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

如果将程序编译为 myprog 可执行文件,并以 myprog -20 somefile anotherfile 调用它,那么您将:

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;
}

由您自己来适当地实现 void tail(char * filename); 功能.不要忘记编译所有警告和提示.调试信息,例如在Linux上使用 gcc -Wall -g .使用调试器(在Linux上为 gdb )调试程序.考虑到 fopen 可能失败,并使用 errno 显示适当的错误消息.

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.

请注意,您不需要 fgetline 函数. getline(3)该功能是标准功能(在Posix 2008中),并且正在动态分配行缓冲区.

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.

这篇关于使用已实现功能的C中的Unix尾部程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆