您如何将整个文件内容读入Genie中的字符串变量中?
(我在文档中找不到任何内容。这些文档似乎也分散且不完整。)
Genie语言本身没有内置的文件输入/输出。您将需要使用一个库,这就是为什么在很多地方提供文档的部分原因。有很多选择!
通常,GLib库是此类低级功能的良好起点。Genie在其类型系统中大量使用了GLib,并且默认情况下包括到GLib库的绑定。因此,这是使用GLib的FileUtils的示例:
[indent=4]
init
var filename = "test.txt"
file_loaded:bool = false
contents_of_file:string
try
file_loaded = FileUtils.get_contents( filename, out contents_of_file )
except error:FileError
print( error.message )
if file_loaded
print( @"Contents of $filename:
$contents_of_file")
编译:
valac fileutils_example.gs
这个例子利用了Genie的:
var
keywod进行类型推断out
参数contents_of_file
contents_of_file
在try...except
块外声明来确定规则@""
用于调用变量to_string()
方法的语法GLib库包含一个附加组件GIO,它提供异步输入/输出和基于流的API。下一个示例是一个非常基本的示例,与上面的操作相同,但是使用了GIO接口:
[indent=4]
init
var file = File.new_for_path( "test.txt" )
file_loaded:bool = false
contents_of_file:array of uint8
try
file_loaded = file.load_contents( null, out contents_of_file, null )
except error:Error
print( error.message )
if file_loaded
text:string = (string)contents_of_file
print( @"Contents of $(file.get_basename()):
$text")
编译:
valac --pkg gio-2.0 -X -w fileinputstream_example.gs
注意事项:
--pkg gio-2.0
使用GIO库,--pkg glib-2.0
在前面的示例中不需要,因为默认情况下已完成contents_of_file:array of uint8
是一个缓冲区和一个out
参数load_contents ()
-X -w
选项可valac
禁止在guint8
期望时从C编译器传递警告char
(string)contents_of_file
GLib.Mainloop
或派生循环,则可以让GIO在后台线程中加载文件:file_loaded = yield file.load_contents_async( null, out contents_of_file, null )
null
则可null
以为参数指定默认值,以便它们成为可选参数,但GIO绑定中未使用该技术。最后,可能还有其他更适合您需求的库。例如,Posix.FILE是读取和写入文件的另一种方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句