How do you read the entire file contents into a string variable in Genie?
(I cannot find anything in docs. The docs also seem scattered and incomplete.)
How do you read the entire file contents into a string variable in Genie?
(I cannot find anything in docs. The docs also seem scattered and incomplete.)
The Genie language itself does not have file input/output built in. You will need to use a library and that is partly why the documentation is in a lot of places. There is a lot of choice!
As a general rule, a good starting place for low-level functionality like this is the GLib library. Genie makes heavy use of GLib for its type system and includes the bindings to the GLib library by default. So here is an example using GLib's FileUtils:
Compile with:
valac fileutils_example.gsThis example makes use of Genie's:
varkeywodoutparametercontents_of_filecontents_of_fileoutside thetry...exceptblock@""syntax for calling a variable'sto_string()methodThe GLib library contains an additional component, GIO, that provides asynchronous input/output and a streams based API. The next example is a very basic example that does the same as above, but using the GIO interfaces:
Compile with:
valac --pkg gio-2.0 -X -w fileinputstream_example.gsPoints to note are:
--pkg gio-2.0uses the GIO library,--pkg glib-2.0was not needed in the earlier example because that is done by defaultcontents_of_file:array of uint8is a buffer and anoutparameter forload_contents ()-X -woption tovalacsuppresses the warning from the C compiler thatguint8is being passed when it was expectingchar(string)contents_of_fileGLib.Mainloopor a derived loop, you could get GIO to load the file in a background thread:file_loaded = yield file.load_contents_async( null, out contents_of_file, null )nullarguments could have been given default values ofnullso they become optional, but that technique was not used in the GIO bindingsFinally, there may other libraries that better fit your needs. For example Posix.FILE is another way of reading and writing files.