genie

Read entire file contents as a string


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.)


Solution

  • 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:

    [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")
    

    Compile with:

    valac fileutils_example.gs

    This example makes use of Genie's:

    The 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:

    [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")
    

    Compile with:

    valac --pkg gio-2.0 -X -w fileinputstream_example.gs

    Points to note are:

    Finally, there may other libraries that better fit your needs. For example Posix.FILE is another way of reading and writing files.