Work on `id`. Still missing some functionality.
[lab.git] / cat.c
blob8102f743b46b7a7d16e09fb8c40eecea5129b4c7
1 /* `cat.c` - con*cat*enate and print files
2 Copyright (c) 2022, Alan Potteiger
3 See `LICENSE` for copyright and license details */
5 #define _POSIX_C_SOURCE 200809L
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <errno.h>
11 #include <unistd.h>
13 /* usage: cat [-u] [file...] */
15 int
16 main(int argc, char *argv[])
18 FILE *in;
19 int uflag;
20 char ch;
22 argc--;
23 argv++;
25 if (argc < 1)
26 goto noarg;
28 /* -u? */
29 if (argv[0][0] == '-' && argv[0][1] == 'u') {
30 uflag = 1;
31 /* disable buffering for stdout, if the request cannot be
32 honored we'll print a brief message to stderr and continue
33 regular execution */
34 if (setvbuf(stdout, NULL, _IONBF, 0) == EOF)
35 fputs("cat: -u: unbuffer request failed\n", stderr);
36 argc--;
37 argv++;
40 /* interpret remaining arguments as files to be read and printed */
41 for (; argc != 0; argc-- && argv++) {
42 if (*argv[0] == '-')
43 in = stdin;
44 else
45 in = fopen(argv[0], "r");
47 if (in == NULL) {
48 fprintf(stderr, "cat: %s: %s\n", argv[0],
49 strerror(errno));
50 continue;
53 /* disable buffering for our input stream, if the request
54 cannot be honored we'll print a brief message to stderr and
55 continue regular execution */
56 if (uflag) {
57 if (setvbuf(in, NULL, _IONBF, 0) == EOF)
58 fputs("cat: -u: unbuffer request failed\n",
59 stderr);
62 while ((ch = fgetc(in)) != EOF)
63 putchar(ch);
65 fclose(in);
68 return 0;
70 noarg:
71 if (argc < 1) {
72 while ((ch = getchar()) != EOF)
73 putchar(ch);
76 return 0;