1

I see following code example on this Vala documentation page:

public static int main (string[] args) {
    // Opens "foo.txt" for reading ("r")
    FileStream stream = FileStream.open ("foo.txt", "r");
    assert (stream != null);

    // buffered:
    char buf[100];
    while (stream.gets (buf) != null) {
        print ((string) buf);
    }

    return 0;
}

However, I cannot find a close() function. I want to open file once for reading and later again for writing. Is it safe to do so without a close in between?

(I do not want to use a+ etc mode which permit both reading and writing as both may not be needed while running the application.)

1 Answer 1

1

There are two key items at play:

  1. The FileStream class is a binding to standard C library functions (e.g. open for fopen, read for fread, etc.). (See: this Stack Overflow answer for a good overview of various file APIs)
  2. Vala does automatic reference counting and will free objects for you (See: Vala's Memory Management Explained).

Now if we look at the definition for the FileStream Vala binding, we see:

[ CCode ( cname = "FILE" , free_function = "fclose" ) ]
public class FileStream

Notice the free_function = "fclose" part. This means that when it comes time for Vala to free a FileStream object, it will implicitly call fclose. So no need to attempt this manually. (Also see: Writing VAPI files under the Defining Classes section for details on free_function)

What this means for you is that once your stream object goes out of scope, reference count hits 0, etc. it will get cleaned up for you as you would expect with any other object. You can safely open the file for reading again later by using FileStream.open and getting a new FileStream object.

2
  • Very well explained. So it is closed once it is out of scope. Hence, if I try to open "foo.txt" file again (now in "a+" mode) in main function itself, there will be an error? Or will the file be closed automatically and reopened in new mode?
    – rnso
    Oct 5, 2022 at 17:59
  • @rnso That's a good question, I'm not 100% sure how it would behave. Since it's ultimately calling C library functions, I think it's safe to say that it would behave the same as not calling close if this was written in C. It should be safe to open the file multiple times for reading, but obviously you'd need to be careful about writes. At the risk of being "that person" on Stack Overflow, I personally use the GLib.FileInputStream and FileOutputStream APIs for file operations because I think the interface is a bit clearer.
    – avojak
    Oct 5, 2022 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.