1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
/*
parse_noempty_strtox - wrappers for strtod and strtol for command line parsing
Copyright (C) 2012 Boud Roukema
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
See also http://www.gnu.org/licenses/gpl.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include "lib/parse_noempty_strtox.h"
int parse_noempty_strtox(char *string, /* INPUTS */
const char *error_message_1,
const char *error_message_2,
char value_type, /* 'd' or 'l' */
int fatal_fail,
void *valid_value, /* OUTPUTS */
char ** endptr
){
double tmp_double=-9e9;
long tmp_long=-999;
int return_value;
const int base = 10; /* hardwired; possible TODO: could generalise this */
errno=0;
switch(value_type)
{
case 'l':
tmp_long=strtol(string,endptr,base);
break;
case 'd':
tmp_double=strtod(string,endptr);
break;
default:
printf("parse_noempty_strtox: Error. Called with invalid type: %c.\n",
value_type);
if(1==fatal_fail)exit(EXIT_FAILURE);
break;
};
if(errno != 0 || *endptr == string){
printf("%s",error_message_1);
switch(fatal_fail)
{
case -1:
printf(" Comment: failed to read ");
break;
case 0:
default:
printf(" Warning: failed to read ");
break;
case 1:
printf(" Error: failed to read ");
break;
};
printf("%s",error_message_2);
printf(" value.\n");
if(1==fatal_fail)exit(EXIT_FAILURE);
return_value=1;
}else{
if('l'==value_type){
*(long*)valid_value= tmp_long;
}else{ /* default is 'd' */
*(double*)valid_value = tmp_double;
};
return_value=0;
};
return return_value;
}
|