Simple Error Handling in C

Currently I’ve got the pleasure to do some coding in C. There’s nothing wrong with that, but things can get a bit uncomfortable for those spoilt by languages like Python or Java. So it’s nice to have a library of useful functions from various areas, which I accumulated over the years.

One of them is err_quit(). It provides a convenient way to exit the program after printing an error message, a pattern often used in command line tools. The function supports a format string and a variable number of arguments, just like the printf(3) family of functions. And the best thing: It’s all ANSI C compliant.

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

void err_quit(const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);

        vfprintf(stderr, fmt, ap);

        va_end(ap);

        exit(EXIT_FAILURE);
}
Advertisements
This entry was posted in c/c++ and tagged , . Bookmark the permalink.

One Response to Simple Error Handling in C

  1. finch says:

    That’s a good one. :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s