def get_avail_mb(): int
f: FILE = FILE.open("/proc/meminfo","r")
s: string = ""
while s.length < 200 do s += " "
f.read(s, 200, 1)
var a = s.split("\n")
s = a[2]
t: string = ""
for var i = 0 to s.length
if s[i] <= '9' && s[i] >= '0'
t += s[i].to_string()
return int.parse(t)/1000
Notice how I allocate the string to 200 charaters with while s.length < 200 do s += " "
to read bytes into this string from the file? Is there a better way to set the length of a string to N characters in Genie other than appending space character N times?
Probably the best way is to create a fixed size array as a buffer and cast the buffer to a string. This avoids some C warnings when compiled. Compile with valac --pkg posix example.gs
:
[indent=4]
uses
Posix
init
print( @"Available memory: $(get_avail_mb()) MB" )
def get_avail_mb():int
f:FILE = FILE.open("/proc/meminfo","r")
buffer:uint8[200]
f.read(buffer, 200, 1)
result:int = 0
match_result:MatchInfo
if ( /^MemAvailable:\s*([0-9]*).*$/m.match(
(string)buffer,
0,
out match_result
))
result = int.parse( match_result.fetch( 1 ))/1000
return result
Alternatively you could try string.nfill ():
[indent=4]
uses
Posix
init
print( @"Available memory: $(get_avail_mb()) MB" )
def get_avail_mb():int
f:FILE = FILE.open("/proc/meminfo","r")
s:string = string.nfill( 200, ' ' )
f.read(s, 200, 1)
result:int = 0
match_result:MatchInfo
if ( /^MemAvailable:\s*([0-9]*).*$/m.match(
s,
0,
out match_result
))
result = int.parse( match_result.fetch( 1 ))/1000
return result