Skip to content

Instantly share code, notes, and snippets.

@aahnik
Last active July 27, 2023 20:12
Show Gist options
  • Save aahnik/3bacc3827edf288ada2ef03e56a482b0 to your computer and use it in GitHub Desktop.
Save aahnik/3bacc3827edf288ada2ef03e56a482b0 to your computer and use it in GitHub Desktop.
Implementation of cat from book The C Programming Language 2e
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
void filecopy(FILE *, FILE *);
if (argc == 1) {
// no input, so copy stdin
filecopy(stdin, stdout);
}
else {
while (--argc > 0) {
if ((fp = fopen(*++argv, "r")) == NULL) {
printf("cat: Can't open file '%s'", *argv);
return 1;
} else {
filecopy(fp, stdout);
fclose(fp);
}
}
}
return 0;
}
void filecopy(FILE *ifp, FILE *ofp) {
int c;
while ((c = getc(ifp)) != EOF) {
putc(c, ofp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment