Skip to content

Instantly share code, notes, and snippets.

@muaddib1971
Created January 21, 2017 05:01
Show Gist options
  • Select an option

  • Save muaddib1971/0cb24bcc4732eddee67e8676bea48d86 to your computer and use it in GitHub Desktop.

Select an option

Save muaddib1971/0cb24bcc4732eddee67e8676bea48d86 to your computer and use it in GitHub Desktop.
A program that takes an error number and outputs the correct error message that matches it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define ONE_ARG 2
#define DECIMAL 10
typedef enum { FALSE, TRUE } BOOLEAN;
BOOLEAN str_to_int(const char input[], int * output)
{
char * end;
long lresult;
/* extract the number */
lresult = strtol(input, &end, DECIMAL);
/* was there non-numeric data ? */
if(*end)
{
fprintf(stderr, "Error: non-numeric data entered.\n");
return FALSE;
}
/* is the value outside the range of an int */
if(lresult < INT_MIN || lresult > INT_MAX)
{
fprintf(stderr, "Error: the number was outside the valid"
" range for an int.\n");
return FALSE;
}
*output = lresult;
return TRUE;
}
int main(int argc, char ** argv)
{
int err_code;
/* check that there is only one argument */
if(argc != ONE_ARG)
{
fprintf(stderr, "Error: please provide a single number "
"to get an error message for.\n");
return EXIT_FAILURE;
}
/* extract the number from argv[1] */
if(!str_to_int(argv[1], &err_code))
{
return EXIT_FAILURE;
}
/* output the error message */
printf("%s\n", strerror(err_code));
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment