Statalist The Stata Listserver

[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: Files left open in Mata

From (William Gould, Stata)
Subject   Re: st: Files left open in Mata
Date   Thu, 19 Oct 2006 09:32:08 -0500

German Rodriguez <grodri@Princeton.EDU> complains that Mata leaves open
files opened by -_fopen()- after an error and helpfully provided a 
program to create the condition and demonstrate the problem.

The situation is this:  Somewhere in a program, German executes 

                fh = fopen("locked.txt", "w")

and then later in the program there is an error.  German fixes the 
mistake and reruns the program, but before he does that, he remembers 
that he needs to erase locked.txt.  He discovers he cannot erase the
files because the file was never closed!  In desperation, German is
forced to -exit- and restart Stata, and that solves the problem.

I have a better solution:

        -------------------------------- closeallfiles.ado ---
        program closeallfiles
                version 9

                forvalues i=0(1)50 {
                        capture mata: fclose(`i')
        -------------------------------- closeallfiles.ado ---

Rather than exit Stata to close the open files, from the Stata prompt, 

        . closeallfiles

More details

-closeallfiles- is more a workaround than a solution.

What German discovered is a bug, but I'm unsure how best to fix it.

Closing all the open files is easy.  The question is, when should they 
be closed?

In an earlier version of Mata, Mata did close all open files on error, but we
removed the feature because we found it irritating when working with Mata
interactively.  If we made the tiniest mistake, the files we had opened
would be closed and we would have to start all over again.  I admit it is
unlikely that anyone else would be working with -fopen()- and -fclose()-
interactively, bug it is possible.

For that reason, I do not suggest that all open files be closed on error, 
although that is a possibility.

Instead, I suggest -mata clear- should close all open files.  

-mata clear- is one of Mata's interpretive commands, 

        : mata clear 

and it clears Mata.  -mata clear- is called by Stata's -clear- command,

        . clear

If we changed -mata clear-, then when German ran into his debugging
situation, he could clear rather than exiting and restarting Stata.
German would have to reload his programs, but I assume that they are
in a do-file and that would not be a problem.

I am open to other suggestions.

I will do nothing until German offers his opinion. 

-- Bill
*   For searches and help try:

© Copyright 1996–2021 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index