Sujet : Re: improve that function (bytes_dig_int)
De : fir (at) *nospam* grunge.pl (fir)
Groupes : comp.lang.cDate : 03. Apr 2024, 22:50:37
Autres entêtes
Organisation : i2pn2 (i2pn.org)
Message-ID : <uukivg$3vq2p$1@i2pn2.org>
References : 1 2
User-Agent : Mozilla/5.0 (Windows NT 5.1; rv:27.0) Gecko/20100101 Firefox/27.0 SeaMonkey/2.24
fir wrote:
fir wrote:
void BytesTest()
{
bytes_load("some.txt");
>
while(bytes_cursor<bytes_size)
{
int value = bytes_dig_int_from_cursor();
if(bytes_cursor>bytes_size) break;
printf("\n %d", value);
}
}
>
>
as to this part i was thinking that using the bytes_cursor
(or how to call it better) would be good idea and would simplify
the usage of it but this loop is also overcomp0-lex so im not sure
if to using sorta global variable (like "none") wouldnt be better here
>
thsi is odlschool idea and i dont seen its used today but here it
is just simple
>
for(;;)
{
int value = dig_int();
if(none) break;
>
}
>
>
so i revrited no wto use global variable (module variable - it should be rather named module variable
than global variable as i once noted variables in modern c like on windows are not global but module scope - as programs are modules)
int bytes_dig_int()
{
if(bytes_cursor>=bytes_size){ found =0; return 'none'; }
for(;;)
{
SkipBytesTillNumberBegin();
if(bytes_cursor>=bytes_size) { found =0; return 'none'; }
unsigned char* h = &bytes[bytes_cursor];
int value = strtol(h, &h, 10);
if(h>&bytes[bytes_size]) ERROR_EXIT("\n*** ERROR in DigInt - strtol reached after bytes ");
if(h==&bytes[bytes_cursor]) ERROR_EXIT("\n*** ERROR in DigInt - not a number ");
if (errno) ERROR_EXIT("\n*** ERROR in DigInt - out of range ");
bytes_cursor = (int)(h-bytes);
found = 1;
return value;
}
return 0;
}
it is not tested for potential errors though
imo it is also cool fo write a procedure that finds goven
name and then digs int right after that - such simple function
then can be used to read settings from a text file and this is
kinda fun as it assumes nothing about the file format
do no ini no xml etc - you just find a string and take an int after that string and this is funny way (i get a little merry after
noticing that) its also very easy to write
int compare_bytes_at_to_str(int at, unsigned char* str, int len )
{
for(int i=0; i<len;i++)
{
if(bytes[at+i]!=str[i]) return 0;
}
return 1;
}
int bytes_find(char* str)
{
int len = StrLen(str);
for(int i=bytes_cursor; i<bytes_size-len+1; i++)
{
if(compare_bytes_at_to_str(i, str, len))
{
bytes_cursor = i + len;
found = 1;
return i;
}
}
found = 0;
return -1;
}
int bytes_take_named_int_value(char* str)
{
bytes_find(str);
if(!found) return 'none';
int value = bytes_dig_int();
if(found) return value;
else return 'none';
}