[comp.sources.d] perror

sja@sirius.uucp (Sakari Jalovaara) (02/27/89)

In article <3526@sugar.uu.net> peter@sugar.uu.net (Peter da Silva) writes:
>Please, folks. If you call perror you have to either avoid doing any other
>system called before you call it, or you have to save and restore errno.

>	myperror(argv[0], argv[optind]);

Here is another way: easy to use, portable in UNIX and ANSI C
(delete the strerror() definition if you have ANSI C libraries.)

---------------------- Cut and save --------------------------------

/*
 * char *errstr ();
 * char *strerror ();
 *
 * Convert errno to an error message.
 *
 * Usage:
 *   fprintf (stderr, "%s: can't open %s: %s\n", program, filename, errstr ());
 *
 */

char *
errstr ()
{
    extern int errno;
    return strerror (errno);
}


/* #ifndef __STDC__ */

/* X3J11/88-158 4.11.6.2 */

char *
strerror (e)
int e;
{
    extern char *sys_errlist[];
    extern int sys_nerr;
    static char unknown[40];

    if (e < sys_nerr && e >= 0)
	return sys_errlist[e];

    sprintf (unknown, "unknown error %d", e);
    return unknown;
}
/* #endif __STDC__ */

--
Sakari Jalovaara (sja@sirius.hut.fi / mcvax!santra!sirius!sja)