coreutils

General Software Utilities
git clone http://git.omkov.net/coreutils
Log | Tree | Refs | README | LICENCE | Download

coreutils/src/cat.c (78 lines, 1.9 KiB) -rw-r--r-- blame download

01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
// cat.c, version 1.0.5
// OMKOV coreutils implementation of POSIX cat
// Copyright (C) 2020, Jakob Wakeling
// MIT Licence

#include "util/error.h"
#include "util/optget.h"

#include <stdbool.h>
#include <stdio.h>

#define VERSION "1.0.5"

static struct lop lops[] = {
	{ "help",    ARG_NUL, 256 },
	{ "version", ARG_NUL, 257 },
	{ NULL, 0, 0 }
};

static inline int cat(const char *file);

static void hlp(void);
static void ver(void);

int main(int ac, char *av[]) { A0 = av[0];
	struct opt opt = OPTGET_INIT; opt.str = "u"; opt.lops = lops;
	for (int o; (o = optget(&opt, av, 1)) != -1;) switch (o) {
	case 'u': { break; }
	case 256: { hlp(); return 0; }
	case 257: { ver(); return 0; }
	default: { return 1; }
	}
	
	// Disable buffering on stdout
	setvbuf(stdout, NULL, _IONBF, 0);
	
	if (opt.ind == ac) { cat("-"); }
	else for (char **p = &av[opt.ind]; *p; ++p) if (cat(*p)) {
		warn("%s: %s", *p, serr());
	}
	
	return warned;
}

/*
	Write a file to stdout using a fixed size buffer.
	If the file path given is "-", then use stdin.
*/
static inline int cat(const char *file) {
	char buf[BUFSIZ * 16]; FILE *fi;
	
	if (file[0] == '-' && file[1] == 0) { fi = stdin; }
	else if (!(fi = fopen(file, "r"))) { return 1; }
	
	for (register size_t c; (c = fread(buf, 1, sizeof (buf), fi));) {
		if (fwrite(buf, 1, c, stdout) != c) { fclose(fi); return 1; }
	}
	
	if (fi != stdin) { fclose(fi); } return 0;
}

/* Print help information */
static void hlp(void) {
	puts("cat - concatenate and print files\n");
	puts("usage: cat [-u] [file...]\n");
	puts("options:");
	puts("  -u         Disable output buffering (ignored)");
	puts("  --help     Display help information");
	puts("  --version  Display version information");
}

/* Print version information */
static void ver(void) {
	puts("OMKOV coreutils cat, version " VERSION);
	puts("Copyright (C) 2020, Jakob Wakeling");
	puts("MIT Licence (https://opensource.org/licenses/MIT)");
}