Snippet. Vala. Get Text From File with FileUtils

This Vala snippet shows how to get the contents a file using FileUtils.

The FileUtils class from the GLib package is very convenient, when working with text files. To get the text contained in a text file use the method get_contents of the class FileUtils. If the file does exist, its content will be returned as string.

try {
    string contents;
    FileUtils.get_contents("data.txt", out contents);
    stderr.printf (contents);
} catch(FileError e) {
    stderr.printf ("Error: %s\n", e.message);

Note. This method will throw an error, if any problem arise, for instance if the file does not exist. Therefore it must be surrounded with a try...catch... clause.

Updated on: 24 Apr 2024