如何将整个文件内容读入 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
使用关键字进行类型推断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
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是另一种读写文件的方式。