• HEAD 명령어를 만들어보자. head 명령어는 파일의 처음 몇 줄만을 출력해주는 명령어이다.

  • 아래는 head 명령어를 실행하는 예이다.

$ head -n 5 file.c

cat file.c | head -n 5
  • 위처럼 파일의 이름을 실행인자로 전달하면, 그 파일의 처음 몇 줄만을 출력한다. 또한 인자로 파일 이름을 지정하지 않은 경우에는 표준 입력에서 읽어서 출력하는데, 이와 같은 동작이 리눅스에서는 일반적이다.

head.c


  • head 명령어는 비교적 간단한 프로그램이지만, 그렇다고 만만하지는 않다. 따라서 일부 기능만 포함된 버전을 만들고 조금씩 기능을 추가하는 것이 좋다.

  • 이렇게 단계적으로 기능을 추가해나가는 것이 일반적으로 프로그램을 만들 때 좋은 접근 방법이다.

  • 특히 초보자들은 처음부터 모든 기능을 다 구현하려다 보면 뒤죽박죽이 될 수 있다.

  • 따라서 처음에는 아주 쉬운 기능을 확실히 돌아가게 만들고 나서, 조금씩 기능을 덧붙여 나가는 것이 확실한 방법이다.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

static void do_cat(const char *path);
static void die(const char *s);

int main(int argc, char *argv[]) {
  int i;
  if (argc < 2) {
    fprintf(stdout, "%s: file name not given\n", argv[0]);
    exit(1);
  }
  for (i = 1; i < argc; i++) {
    do_cat(argv[i]);
  }
  exit(0);
}

#define BUFFER_SIZE 2048

static void do_cat(const char *path)
{
  int fd;
  unsigned char buf[BUFFER_SIZE];
  int n;

  fd = open(path, O_RDONLY);
  if (fd < 0) die(path);

  for (;;) {
    n = read(fd, buf, sizeof buf);
    if (n < 0) die(path);
    if (n == 0) die(path);
    if (write(STDOUT_FILENO, buf, n) < 0) die(path);
  }
  if (close(fd) < 0) die(path);
}

static void die(const char *s)
{
  perror(s);
  exit(1);
}

참고 문헌

>> Home