Created
January 20, 2021 14:16
-
-
Save mahata/fa52452ec5bd95d6e792fd1ed71c5cd7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 本章で作った cat コマンドを改造して、コマンドライン引数でファイル名が渡されなかったら標準入力を読むようにしなさい。 | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
static void do_cat(int fd, const char *s); | |
static void die(const char *s); | |
int main(int argc, char *argv[]) { | |
if (argc == 1) { | |
do_cat(STDIN_FILENO, "STDIN"); | |
} else { | |
for (int i = 1; i < argc; i++) { | |
int fd; | |
fd = open(argv[i], O_RDONLY); | |
do_cat(fd, argv[i]); | |
} | |
} | |
exit(0); | |
} | |
#define BUFFER_SIZE 2048 | |
static void do_cat(int fd, const char *path) { | |
unsigned char buf[BUFFER_SIZE]; | |
if (fd < 0) die(path); | |
for (;;) { | |
int 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); | |
} | |
static void die(const char *s) { | |
perror(s); | |
exit(1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment