error messages (was Re: friendly messages)

Chris Torek chris at mimsy.UUCP
Tue Apr 4 00:27:18 AEST 1989


In article <7555 at phoenix.Princeton.EDU> bernsten at phoenix.Princeton.EDU
(Dan Bernstein) writes:
>  char *err(errno)
>  int errno;
>  {
>   if ...
[compressed]
>   else
>     return(sys_errlist[errno]);
>  }

This function is in the pANS, where it is called `strerror'.  (The
implementation details---sys_errlist[], etc.---are not, but the function
that does what the one above does is called strerror.)

A slightly shorter test for the error number is

	if ((unsigned)errno >= sys_nerr)
		<out of range>
	else
		<in range; use sys_errlist>

>This is not a high-level routine, nor should it be. Instead of
>attempting to build the generality of printf() into the error
>message printer, I just reference err(errno) and use printf()
>or sprintf() as usual. Why rebuild what's already there?

Having an error printer that also exits is more convenient.  Since
the latter is cheap (using vfprintf), why not provide both?  I have
the function

	error(int exitcode, int err, char *fmt, ...)

in our C library.  It prints to stderr the program name (hidden away in
the external `_argv0', set by /lib/crt0.o), the string given by fmt+...,
appends strerror(err < 0 ? errno : err) if err != 0, appends a newline,
and then does an exit(exitcode) if exitcode != 0.  (err is almost always
given as -1, and should perhaps be replaced with a boolean.  If you want
something fancier, strerror() is there.)  It is very handy:

	if (argc < 2)
		error(2, 0, "usage: %s filename", argv[0]);
	if ((fd = open(argv[1], mode)) < 0)
		error(1, -1, "cannot open %s", argv[1]);
	...

Without it, you need

	extern int errno;

	if (argc < 2) {
		(void) fprintf(stderr, "%s: usage: %s filename\n",
		    argv[0], argv[0]);
		exit(2);
	}
	if ((fd = open(argv[1], mode)) < 0) {
		(void) fprintf(stderr, "%s: cannot open %s: %s\n",
		    argv[0], argv[1], strerror(errno));
		exit(1);
	}

The difference is small, but significant (somewhat like using E-
notation for large floating point numbers---1.14E75 is easier to
read and write than 1140000000...000).
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.unix.wizards mailing list