getenv_int.c

Go to the documentation of this file.
00001 #include <stdlib.h>
00002 #include <stdio.h>
00003 #include <errno.h>
00004 
00005 #include "utility.h"
00006 
00007 /* Check for an integer in an environment variable, returning the
00008    integer value or a provided default value */
00009 
00010 int 
00011 getenv_int(char* name, int defval)
00012 {
00013   char *envstr = NULL;
00014   long int longval = -1;
00015   char *endptr;
00016   extern int errno;
00017 
00018   if (name == NULL) return defval;
00019 
00020   /* Env variable does not exist */
00021   if ((envstr = getenv(name)) == NULL) return defval;
00022 
00023   /* Convert to long, checking for errors */
00024   longval = strtol(envstr, &endptr, 10);
00025   if ((errno == ERANGE) || (longval==0 && endptr==envstr))
00026     return defval;
00027 
00028   return (int)longval;
00029 }