4 ms·
Personally I'd just go the wrapper approach and ignore errno entirely. #include <assert.h> #include <ctype.h> #include <limits.h> #include <stdbool.h>
by spyrja 1y ago
Personally I'd just go the wrapper approach and ignore errno entirely.
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
bool copy_str_to_long_long(const char* str, long long* ptr) {
while (isspace(*str))
++str;
if (*str == 0)
return false;
char* parsed = NULL;
long long value = strtoll(str, &parsed, 0);
while (isspace(*parsed))
++parsed;
if (*parsed != 0)
return false;
*ptr = value;
return true;
}
long long str_to_long_long(const char* str) {
long long result;
assert(copy_str_to_long_long(str, &result));
return result;
}
bool copy_str_to_long(const char* str, long* ptr) {
long long buffer;
if (!copy_str_to_long_long(str, &buffer) || buffer < LONG_MIN || buffer > LONG_MAX)
return false;
*ptr = buffer;
return true;
}
long str_to_long(const char* str) {
long result;
assert(copy_str_to_long(str, &result));
return result;
}
/*
...define copy_str_to_short, copy_str_to_int32, etc...
*/