Created
October 10, 2019 13:34
-
-
Save chiangqiqi/05b8944586ff3a591e13a7ae75277d58 to your computer and use it in GitHub Desktop.
reimplement linux cat
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
#include <stdlib.h> | |
#include <string.h> | |
#include <stdio.h> | |
#include <err.h> | |
#include <fcntl.h> | |
#include <sys/stat.h> | |
void cat(int rfd) { | |
int wfd; | |
static char *buf; | |
static size_t bsize; | |
struct stat sbuf; | |
wfd = fileno(stdout); | |
if (fstat(wfd, &sbuf)) | |
err(1, "stdout"); | |
bsize = sbuf.st_blksize; | |
buf = malloc(bsize); | |
if (!buf) | |
err(1, 0); | |
ssize_t nr, nw; | |
int offset = 0; | |
nr = read(rfd, buf, bsize); | |
while (nr > 0) { | |
for (offset = 0; nr > 0; nr-=nw, offset += nw) { | |
nw = write(wfd, buf, nr); | |
if (nw < 0) | |
err(1, "stdout"); | |
} | |
} | |
nr = read(rfd, buf, bsize); | |
} | |
int main(int argc, char *argv[]) { | |
// the first element of argv is the command itself | |
++argv; | |
int fd; | |
fd = fileno(stdin); | |
while (*argv) { | |
// do the thing | |
fd = open(*argv, O_RDONLY); | |
if (fd < 0) | |
err(1, "%s", *argv); | |
cat(fd); | |
++argv; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment