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?
Why not use
fscanf(fd, "%d%n%c", &myInt, &pos, &nextChar);
Then check that pos is where you expect it to be and the next character is not a digit?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With