cat.c
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define CHUNK 128
int cat(int fd);
void cleanup(void);
int fd = STDIN_FILENO;
int main(int argc, char **argv) {
atexit(cleanup);
if(argc >= 2) {
char *path = argv[1];
fd = open(path, O_RDONLY);
if(fd == -1) return 1;
}
return cat(fd);
}
void cleanup(void) {
if(fd != STDIN_FILENO) close(fd);
}
int cat(int fd) {
uint8_t buf[CHUNK + 1] = {0};
ssize_t count = 0;
while((count = read(fd, buf, CHUNK))) {
if(count == -1) return 1;
printf("%s", buf);
memset(buf, 0, CHUNK);
}
return 0;
}
I: Reimplementing the coreutils in C