Home > database >  Why string is not being written to file here
Why string is not being written to file here

Time:09-29

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?

CodePudding user response:

The problem is here:

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

You open the file with a mode of "rw". That is not a valid mode, see the documentation at: https://valadoc.org/glib-2.0/GLib.FileStream.open.html

Mode is used to determine the file access mode.
Mode:   Meaning:    Explanation:    File already exists:    File does not exist:
"r"     read    Open a file for reading     read from start     failure to open
"w"     write   Create a file for writing   destroy contents    create new
"a"     append  Append to a file    write to end    create new
"r "    read extended   Open a file for read/write  read from start     error
"w "    write extended  Create a file for read/write    destroy contents    create new
"a "    append extended     Open a file for read/write  write to end    create new

You can use "w" for writing or "w " for reading and writing, the same with "a" and "a " will preserve the existing file and write to the end.

CodePudding user response:

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.

  • Related