[alt.sources] a simple pager

kyle@xanth.UUCP (08/14/87)

Here's a very simple pager that should work under any UN*X/C implementation.
I wrote this for a friend who must use a horrible implementation of SysV.
Hope this helps someone out there.

kyle jones   <kyle@odu.edu>   old dominion university, norfolk, va
---------------------------------------------------------------------------
/*
 * p - a simple pager
 *
 * p [files]	no files means to use stdin
 *
 * Copyright (C) 1987 Kyle E. Jones
 *
 * This software may be redistributed provided this notice appears on all
 * copies and that the further free redistribution of this software is not
 * restricted in any way.
 *
 * This software is distributed 'as is', without warranties of any kind.
 */

#include <stdio.h>

#define LINES	24

int Errors;
FILE *tty;

void showline(), showfile();

main(argc, argv)
    int argc;
    char **argv;
{
    char msgbuf[256];
    int multiple = 0;

    if (argc == 1)
      showfile((char *)0);
    else {
	if (argc > 2)
	  multiple = 1;
	for (argc--,argv++; argc > 0; argc--, argv++) {
	    if (multiple) {
		sprintf(msgbuf, "=== %s ===============\n", *argv);
		showline(msgbuf);
	    }
	    showfile(*argv);
	}
    }
    exit(Errors);
}

void
showfile(file)
    char *file;
{
    FILE *f;
    char line[1024];
    char *more, *fgets();

    if (tty == 0) {
	tty = fopen("/dev/tty", "r");
	if (tty == 0 && file == 0) {
	    fprintf(stderr, "Warning: no access to /dev/tty so I can't page stdin.\n");
	    return;
	}
	else
	  tty == stdin;
    }
    if (file == 0)
      f = stdin;
    else {
	f = fopen(file, "r");
	if (f == 0) {
	    fprintf(stderr, "%s: cannot open\n", file);
	    Errors++;
	    return;
	}
    }
    more = line;
    while (more) {
	line[0] = '\0';
	more = fgets(line, 1024, f);
	showline(line);
    }
    if (f != stdin)
      fclose(f);
}
void
showline(line)
    char *line;
{
    static linecount;

    if (linecount == LINES - 2) {
	int length = strlen(line);
	if (line[length-1] == '\n')
	  line[length-1] = '\0';
    }
    fputs(line, stdout);
    if (++linecount == LINES - 1) {
	getc(tty);
	linecount = 0;
    }
}