Let’s say I have a file of decimal numbers which should be values that can fit in an int, but I want to programmatically verify the content of this file to check for overflows. Is there an easy way to check if any of the numbers will over flow an integer?
Ex. file –
name: test.txt
value: 4343214321423142314
If I were to loop and do fscanf(fd, "%d", &myint) we would return a successful indication but the number stored in myint would be incorrect.
Likewise if I were to read it in to a character array fscanf(fd, "%s", &mystr) and blindly call atoi(mystr) it would return success but with an incorrect result.
Given the second example of reading it into a string it would be possible to do something like:
char buf[11] = {'\0'};
sprintf(buf, "%d", INT_MAX);
fscanf(fd, "%s", &mystr);
if(strcmp(mystr, buf) > 0)
// handle error case
but is there an easier way to do this without needing the extra array and string compare function?
According to scanf(3) man page, the conversion would fail with
errnoset toin your case. So I’ll just check the result of
scanforfscanfand useerrno.