End-of-file character (was script > mumble)

Richard A. O'Keefe ok at quintus.uucp
Wed Oct 5 10:44:56 AEST 1988


In article <4975 at saturn.ucsc.edu> haynes at saturn.ucsc.edu (Jim Haynes - Computer Center) writes:
>So - I'm thinking of sticking in something along the lines of
>	if (!isatty(1))
>		fprintf(stderr, "Redirecting output may not be what
>		you have in mind.  Type a ctrl-D if you want to start
>		over.\n");

Please, anyone who is thinking of doing something like that, DON'T
hardwire "ctrl-D" into your program.  Mention the end-of-file character
the user has assigned, whatever that is.  Just to make life easier
for people who would like to extend this elementary courtesy to the
users of their programs, here's some source code:

: execute this with sh
cat >eofchar.c <<'ENDOFFILE'
/*  File   : eofchar.c
    Author : Richard A. O'Keefe @ Quintus Computer Systems, Inc
    Purpose: Return name of user's end-of-file character

    Compile: cc -DBSD -c eofchar.c		# on 4.x BSD
	     cc -DUSG -c eofchar.c		# on System V
	     cc -DTEST -DBSD eofchar.c		# to test it

    Usage:   eofchar()
	     returns a string which identifies the user's end-of-file
	     character.  A static buffer is used, but this value is not
	     likely to change, so that's no problem.  It is possible that
	     no end-of-file character may be assigned, in which case the
	     value shown is "exit", which is what you type to a shell to
	     stop it.

    Error:   if the end-of-file character cannot be determined, NULL is
	     returned.  (This is distinct from it being determined that
	     there is no end-of-file character.)
*/

#include <stdio.h>
#ifdef	BSD

#include <sgtty.h>

#define	TIO_GET_CHARS	TIOCGETC
#define	TIO_CHR_STRUCT	tchars
#define	TIO_CHR_FIELD	t_eofc

#endif

#ifdef	USG

#include <termio.h>

#define	TIO_GET_CHARS	TCGETA
#define	TIO_CHR_STRUCT	termio
#define	TIO_CHR_FIELD	c_cc[VEOF]

#endif

#ifndef	TIO_GET_CHARS

ERROR: either BSD or USG must be defined;

#endif


char *eofchar()
    {
	int fd;
	struct TIO_CHR_STRUCT info;
	int ch;
	static char buffer[12];

	if (!(isatty(fd=2) || isatty(fd=1) || isatty(fd=0))) {
	    fd = open("/dev/tty", 0);
	    if (fd < 0) {
		perror("Cannot open /dev/tty");
		return NULL;
	    }
	}
	if (ioctl(fd, TIO_GET_CHARS, &info) < 0) {
	    perror("Cannot obtain terminal characters");
	    if (fd > 2) (void) close(fd);
	    return NULL;
	}
	if (fd > 2) (void) close(fd);
	ch = info.TIO_CHR_FIELD;
	if (ch == 127) return "DELETE";
	if (ch == -1)  return "exit";
	if (ch >= 32)  (void) sprintf(buffer, "%c", ch); 
	else	       (void) sprintf(buffer, "Control-%c", ch+64);
	return buffer;
    }

#ifdef	TEST
main()
    {
	printf("Your end-of-file character is %s\n", eofchar());
	exit(0);
    }
#endif

ENDOFFILE



More information about the Comp.unix.wizards mailing list