error() function
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <errno.h>
/*
***********
* swerr() *
***********
PURPOSE: Report errors detected during software execution to the
standard error device.
PRE: An error has been detected,
`prog_name' is a global variable with the program's name.
POST: A detailed error message has been sent to the standard error
device. The message includes the paramaters as descibed below.
If the `error_level' was not 0 then the program has been halted
with a message and a failure code has been returned to the O/S
(in the program's exit value). The program may also exit with
the same error indication if this function detects an error
while writing to the standard error device.
NOTE: Adapted from error() (p.174) of K&R II
Advice from Jutta Degener about use of const acknowledged
*/
void swerr(char const *proc, /* function where the error
occurred, not necessarily where
swerr() was called from */
const int error_level, /* indicates severity of error */
char *format, ...) /* printf()-like */
{
extern char * progname;
int err_num = errno;
int status;
va_list args;
status = fprintf(stderr, "%s [%s()] ", progname, proc);
va_start(args, format);
if (EOF != status) {
status = vfprintf(stderr, format, args);
}
va_end(args);
if (err_num) { /* error reported by library call (includes '\n') */
status = fprintf(stderr, ", ");
errno = err_num; /* use stored value in case
fprintf() changes it */
perror(NULL); /* error message from library call */
} else {
if (EOF != status) {
status = fprintf(stderr, "\n");
}
}
if ((! error_level) || (EOF == status)) {
exit(EXIT_FAILURE);
}
}/* swerr() */
[Back to Annotations on K&R II]
Last updated by J. Blustein on 3 January 1998.
This document is copyright by its author, J. Blustein <jamie@csd.uwo.ca>.