Snippet. Vala. Reading a File

This snippet shows how to read file contents with Vala. Before reading the file, the snippet checks if the file exists.

File file = File.new_for_path("Hello_World.txt");
try {
    if(file.query_exists() == true){
        var dis = new DataInputStream (file.read ());
        string line;
        // Read lines until end of file (null) is reached
        while ((line = dis.read_line (null)) != null) {
            stdout.printf ("%s\n", line);
        }
    }
} catch (Error e) {
    stderr.printf ("Error: %s\n", e.message);
}

Updated on: 03 Dec 2024