Skip to content

Instantly share code, notes, and snippets.

@akkijp
Last active October 22, 2015 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkijp/c9059deb397da3992ef4 to your computer and use it in GitHub Desktop.
Save akkijp/c9059deb397da3992ef4 to your computer and use it in GitHub Desktop.
catコマンドを作る! linuxのファイルディスクリプタを使って、ファイルから端末へ出力する
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFER_SIZE 2048
static void die(const char *s){
perror(s);
exit(1);
}
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) break;
if(write(STDOUT_FILENO, buf, n) < 0) die(path);
}
if(close(fd) < 0) die(path);
}
int main(int argc, char *argv[]){
int i;
if(argc < 2){
fprintf(stderr, "%s: file name not given\n", argv[0]);
exit(1);
}
for(i=1; i<argc; i++){
do_cat(argv[i]);
}
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment