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
注意我如何将字符串分配给200个具有while s.length < 200 do s += " "
的字符,以便从文件中将字节读入此字符串?除了追加空格字符N次之外,还有更好的方法将字符串的长度设置为Genie中的N个字符吗?
答案 0 :(得分:4)
可能最好的方法是创建一个固定大小的数组作为缓冲区并将缓冲区转换为字符串。这避免了编译时的一些C警告。使用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
或者您可以尝试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
答案 1 :(得分:0)
是的,只是避免无法处理某些极端情况的可怕的for循环!