Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to read unverified decimal values from a file?

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?

like image 962
Mike Avatar asked Jan 28 '26 09:01

Mike


1 Answers

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?

like image 185
Ed Heal Avatar answered Jan 30 '26 00:01

Ed Heal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!