perror - (was Re: redirecting output)

Michael Meissner meissner at osf.org
Wed Jul 4 00:21:04 AEST 1990


In article <1792 at necisa.ho.necisa.oz> boyd at necisa.ho.necisa.oz (Boyd
Roberts) writes:

| perror(3) is good, but this is better:
| 
|     char	*
|     sysmess()
|     {
| 	extern int	errno;
| 	extern int	sys_nerr;
| 	extern char	*sys_errlist[];
| 
| 	if (errno < 0 || errno >= sys_nerr)
| 	    return "Unknown error";
| 
| 	return sys_errlist[errno];
|     }
| 
|     void
|     could_not(what, with)
|     register char    *what;
|     register char    *with;
|     {
| 	fprintf(stderr, "%s: Could not %s \"%s\". %s\n", my_name, what, with, sysmess());
| 	exit(1);
| 	/* NOTREACHED*/
|     }
| 
| So then we go:
| 
|     if ((fd = open(file, O_RDONLY)) == -1)
|     {
| 	could_not("open", file);
| 	/* NOTREACHED */
|     }
| 
| Of course, my_name is:
| 
| char	*my_name;
| 
| And main() goes:
| 
| 	if ((my_name = strrchr(argv[0], '/')) == NULLSTR || *++my_name == '\0')
| 		my_name = argv[0];
| 
| 
| Boyd Roberts			boyd at necisa.ho.necisa.oz.au
| 
| ``When the going gets wierd, the weird turn pro...''

You probably should use the ANSI name (strerror), and support the use
of old UNIX with sys_errlst and new ANSI with strerror, via:

#include <errno.h>
#ifndef BSD_STRINGS_H
#include <string.h>
#endif

#ifndef HAVE_STRERROR
char *
strerror(e)
{
  extern int	errno;
  extern int	sys_nerr;
  extern char	*sys_errlist[];

  if (e < 0 || e >= sys_nerr)
      return "Unknown error";

  return sys_errlist[e];
}
#endif

void
could_not(what, with)
register char    *what;
register char    *with;
{
  fprintf(stderr, "%s: Could not %s \"%s\". %s\n", my_name, what, with,
	  strerror(errno));
  exit(1);
  /* NOTREACHED*/
}


Not all non-UNIX systems have sys_errlist, and as internationalization
becomes more important, I would expect that people will soon want the
error messages to be presented in the user's native language.  You
also have the problem that old binaries using sys_errlist don't get
new error message strings without relinking.
--
Michael Meissner	email: meissner at osf.org		phone: 617-621-8861
Open Software Foundation, 11 Cambridge Center, Cambridge, MA

Do apple growers tell their kids money doesn't grow on bushes?



More information about the Comp.lang.c mailing list