Linux 유틸리티 테일의 소스 코드를 어떻게 얻을 수 있습니까?

StackOverflow https://stackoverflow.com/questions/1439799

  •  10-07-2019
  •  | 
  •  

문제

이 명령은 정말 유용하지만 소스 코드를 가져와 내부에서 무슨 일이 일어나고 있는지 확인할 수있는 곳.

감사해요 .

도움이 되었습니까?

해결책

꼬리 유틸리티는 Linux의 Coreutils의 일부입니다.

나는 항상 freebsd가 GNU 유틸리티보다 훨씬 더 명확한 소스 코드를 가지고 있음을 발견했습니다. FreeBSD 프로젝트의 Tail.c는 다음과 같습니다.

다른 팁

UCLINUX 사이트 주위를 찌르십시오. 소프트웨어를 배포 했으므로 소스를 어떤 식 으로든 사용할 수 있도록해야합니다.

또는 읽을 수 있습니다 man fseek 그리고 그것이 어떻게 될지 추측하십시오.

NB-- 아래 William의 의견을 참조하십시오. Seek를 사용할 수없는 경우가 있습니다.

당신은 자신의 글을 쓰는 것이 흥미로운 운동이라고 생각할 수 있습니다. UNIX 명령 줄 도구의 대부분은 상당히 간단한 C 코드의 페이지입니다.

코드를 보려면 GNU Coreutils 소스는 gnu.org 또는 좋아하는 Linux 미러 사이트에서 쉽게 찾을 수 있습니다.

/`*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