这个命令确实非常有用,但是我可以在哪里获取源代码以查看内部发生的情况。

谢谢 。

有帮助吗?

解决方案

tail 实用程序是 Linux 上 coreutils 的一部分。

我一直发现 FreeBSD 的源代码比 gnu 实用程序清晰得多。这是 FreeBSD 项目中的 tail.c:

其他提示

绕过uclinux网站。由于他们分发了软件,因此他们需要以某种方式提供源代码。

或者,您可以阅读man fseek并猜测它是如何完成的。

注意 - 请参阅下面的威廉的评论,有些情况下你不能使用搜索。

你可能会发现自己编写一个有趣的练习。绝大多数Unix命令行工具都是一个相当简单的C代码页面。

要查看代码,可以在gnu.org或您最喜欢的Linux镜像站点上轻松找到GNU CoreUtils源代码。

/`*This example implements the option n of tail command.*/`

    #define _FILE_OFFSET_BITS 64
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <errno.h>
    #include <unistd.h>
    #include <getopt.h>

    #define BUFF_SIZE 4096

    FILE *openFile(const char *filePath)
    {
      FILE *file;
      file= fopen(filePath, "r");
      if(file == NULL)
      {
        fprintf(stderr,"Error opening file: %s\n",filePath);
        exit(errno);
      }
      return(file);
    }

    void printLine(FILE *file, off_t startline)
    {
      int fd;
      fd= fileno(file);
      int nread;
      char buffer[BUFF_SIZE];
      lseek(fd,(startline + 1),SEEK_SET);
      while((nread= read(fd,buffer,BUFF_SIZE)) > 0)
      {
        write(STDOUT_FILENO, buffer, nread);
      }
    }

    void walkFile(FILE *file, long nlines)
    {
      off_t fposition;
      fseek(file,0,SEEK_END);
      fposition= ftell(file);
      off_t index= fposition;
      off_t end= fposition;
      long countlines= 0;
      char cbyte;

      for(index; index >= 0; index --)
      {
        cbyte= fgetc(file);
        if (cbyte == '\n' && (end - index) > 1)
        {
          countlines ++;
          if(countlines == nlines)
          {
        break;
          }
         }
        fposition--;
        fseek(file,fposition,SEEK_SET);
      }
      printLine(file, fposition);
      fclose(file);
    }

    int main(int argc, char *argv[])
    {
      FILE *file;
      file= openFile(argv[2]);
      walkFile(file, atol(argv[1]));
      return 0;
    }

    /*Note: take in mind that i not wrote code to parse input options and arguments, neither code to check if the lines number argument is really a number.*/
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top