Languages

Reading text file line by line with GIO

No votes yet
static int main (string[] args) {
    // A reference to our file
    var file = File.new_for_path ("data.txt");
 
    if (!file.query_exists (null)) {
        stderr.printf ("File '%s' doesn't exist.\n", file.get_path ());
        return 1;
    }
 
    try {
        // Open file for reading and wrap returned FileInputStream into a
        // DataInputStream, so we can read line by line
        var in_stream = new DataInputStream (file.read (null));
        string line;
        // Read lines until end of file (null) is reached
        while ((line = in_stream.read_line (null, null)) != null) {
            stdout.printf ("%s\n", line);
        }
    } catch (IOError e) {
        error ("%s", e.message);
    }
 
    return 0;
}