Okay.. First of all, you must understand the purpose of each and every variable in the code.
Lets take the most important two variables.
bpos - This is the
byte
position within the buffer. Whenever we read a byte we advance the position by 1.
bsize - This is the
buffer
size. Whenever we use fread, it returns the number of bytes it actually read from file. Since we read BSIZE blocks, bsize will be always equals to BSIZE except the last read that reach end of file.
Now we can try understanding the code from there.
Here, we read the byte on current position (initially bpos is 0) and advance the byte position.
Say the byte array in array
buffer is {'1', '2', '3', '4', '5' ......... }.
When it runs the above code, c will become '1' and bpos will set to 1 (from 0).
On the next run, c will become '2' and bpos will set to 2 and so on.
When one block of BSIZE is completely processed, bpos will equals to bsize where the code will read another block on the next call.
The last part that you are not clear is,
Code: Select all
if (c >= '0' && c <= '9'){
x = x*10 + (c-'0'); d = 1;
}
else if (d == 1){
return x;
}
The file you read is a TEXT file (not a BINARY file) so you have readable data on this file when you open this on Notepad.
It will contain numbers like, 1234567.... and so on. When you read this to a char array, it will become {'1', '2', '3', '4', '5' ......... }.
What we do here is, if the character we just read is a number (between char '0' and char '9'), then we multiply the previous value of x by 10 (initially this is 0) and add the integer value of char stored in c. According to the example array I have provided above, x will become 1 after the first iteration on the loop.
On the second iteration on the loop, x will become (1 x 10) + 2 = 12.
On the third iteration on the loop, x will become (12 x 10) + 3 = 123.
This process goes until you find EOF (end of file) or you found a non-number character. In both cases, it returns the value of x.
d is used to stop existing from the function if the first number you read is not a number char. Say our array is {'a', '1', '2' ...... }. Then our first char is 'a' which is not a number and it goes to
else if (d == 1){ part which fails since d = 0 initially.
I explain a bit on the following code.
Say you have just read '1' to c. The ACSII value for char '1' is 49. The ASCII value of char '0' is 48. So when you do c - '0', it is 49 - 48 = 1. See ASCII table
here.