2013年5月14日火曜日

システムコールを使ったcatコマンド

ポピュラーなUNIXコマンドの一つであるcatコマンドをC言語で実装します
条件は……

  1. コマンドライン引数を使う
  2. システムコールを使う(open,read,write,close)
  3. printf,puts,fputs,fopen,fdopenなどのライブラリ関数の使用は禁止
ちなみに、引数としてとれるファイル名は1つだけです


解答例:mycat.c(実行ファイル名:mycat)


/* システムコールを使ったcatコマンド */

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

int main(int argc, char *argv[])
{
  int fd;
  char buf[256];
  int len;

  if (argc != 2) {
    printf("usage:./mycat [filename]\n");
    return (1);
  }

  fd = open(argv[1], O_RDONLY);

  if (fd == -1) {
    perror("open");
    return (1);
 }

  while (1) {
    len = read(fd,buf,sizeof(buf));

    if (len > 0){
      write (1, buf, len);
    } else if (len == 0){
      break;
    } else
    perror("read");
    return (1);
    }
  }
  close(fd);
  return (0);
}

0 件のコメント:

コメントを投稿