Prior to calling strtol
, set errno
to 0.
Then after the call, check the value of errno
. If it's 0, you know the call was successful. Addtionally, you'll want to check if *p
is 0. If so, that means the entire string was parsed successfully with no extra characters.
errno = 0;
long conv = strtol(argv, &p, 10);
if (errno)
{
perror("Conversion error");
exit(EXIT_FAILURE);
}
else if (*p)
{
perror("Not all characters converted");
exit(EXIT_FAILURE);
}
The man page also mentions this in the "Notes" section:
Since strtol() can legitimately return 0, LONG_MAX, or LONG_MIN
(LLONG_MAX or LLONG_MIN for strtoll()) on both success and failure,
the calling
program should set errno to 0 before the call, and then determine if an error occurred by checking whether errno has a nonzero
value after the
call.