Search code examples
filevala

Why string is not being written to file here


I am trying following code:

public static void main(){
    var file = FileStream.open("string.txt", "rw");
    assert (file != null);
    try{
        file.puts (new DateTime.now_local ().to_string ());
        file.putc ('\n');   
        file.flush(); 
    } catch(Error e){
        print("Error occurred while writing."); 
    }
}

Above code compiles all right and also runs without any error. However, no change is being made to the "string.txt" file. Where is the error and how can it be corrected?


Solution

  • The simple answer is to use w+ instead of rw:

    var file = FileStream.open("string.txt", "w+");
    

    The documentation for Filestream.open gives a table of the accepted access modes.

    If the file doesn't exist for r mode, which rw seems to be truncated too, then the file fails to open and the assertion fails for me. Also Filestream.open doesn't throw any exceptions so there's a warning about an unreachable catch clause. You may want to look GIO's IOStream if you're wanting to write input/output code that integrates with GLib's main loop for asynchronous code.