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.)
There are two key items at play:
FileStreamclass is a binding to standard C library functions (e.g.openforfopen,readforfread, etc.). (See: this Stack Overflow answer for a good overview of various file APIs)Now if we look at the definition for the FileStream Vala binding, we see:
Notice the
free_function = "fclose"part. This means that when it comes time for Vala to free aFileStreamobject, it will implicitly callfclose. So no need to attempt this manually. (Also see: Writing VAPI files under the Defining Classes section for details onfree_function)What this means for you is that once your
streamobject 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 usingFileStream.openand getting a newFileStreamobject.