Created
October 10, 2019 14:33
-
-
Save chiangqiqi/76cef13e60a66fc7a8126b69c1fbf90a to your computer and use it in GitHub Desktop.
bsdcat
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); | |
// show content of the file | |
++argv; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment