cat - "" means print stdin if!strcmp(file""...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <err.h> /* * cat - concatenate and print * Usage: cat [files] */ /* Print a file that's already been opened. */ static void docat(const char *name, int fd) { char buf[1024]; int len, wr, wrtot; /* * As long as we get more than zero bytes, we haven't hit EOF. * Zero means EOF. Less than zero means an error occurred. * We may read less than we asked for, though, in various cases * for various reasons. */ while ((len = read(fd, buf, sizeof(buf)))>0) { /* * Likewise, we may actually write less than we attempted * to. So loop until we're done. */ wrtot = 0; while (wrtot < len) { wr = write(STDOUT_FILENO, buf+wrtot, len-wrtot); if (wr<0) { err(1, "stdout"); } wrtot += wr; } } /* * If we got a read error, print it and exit. */ if (len<0) { err(1, "%s", name); } } /* Print a file by name. */ static void cat(const char *file) { int fd;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: /* * "-" means print stdin. */ if (!strcmp(file, "-")) { docat("stdin", STDIN_FILENO); return; } printf("Opening File: %s\n", file); /* * Open the file, print it, and close it. * Bail out if we can't open it. */ fd = open(file, O_RDONLY); if (fd<0) { printf("Error Opening File\n"); err(1, "%s", file); } printf("Cat File: %s with fd: %fd\n", file, fd); docat(file, fd); close(fd); } int main(int argc, char *argv) { printf("Executing /bin/cat with %d args.\n", argc); printf("Size of argv is %d\n", sizeof(argv)); int i; for(i = 0; i < argc; i++) { printf("Argv[%d] is %s\n", i, argv[i]); } printf("STDIN_FILENO: %d\n", STDIN_FILENO); if (argc==1) { /* No args - just do stdin */ docat("stdin", STDIN_FILENO); } else { /* Print all the files specified on the command line. */ int i; for (i=1; i<argc; i++) { cat(argv[i]); } } return 0; }...
View Full Document

This note was uploaded on 11/10/2009 for the course CS 536 taught by Professor Lums during the Spring '09 term at Indiana.

Page1 / 2

cat - "" means print stdin if!strcmp(file""...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online