Parsing for size with prefixes in C
At some point, I have decided to pass size of the log file created by stdroller.
I thought it will be hard as hell to pass SI prefixes. I was all wrong. It’s a piece of cake to parse the value with format like: ./stdroller --limit=10G or ./stdroller --limit=1k, etc.
All you have to do is to use strtoull function. It returns location of first character that is not a part of your positional system (I am using system with base 10). So, you get index of SI prefix for free. Isn’t that cool?
limit = strtoull( optarg, &next_idx, 10 ); if( *next_idx != '\0' ) { if( *(next_idx + 1) != '\0') { printf("Ups. You have passed incorrect number\n"); exit(1); } else { switch( *next_idx ) { case 'K': case 'k': limit *= pow(10,3); break; case 'M': case 'm': limit *= pow(10,6); break; // you can put additional cases here for G/g, T/t, P/p, etc. default: printf("Ups. Incorrect SI prefix\n"); exit(1); } } }