Statalist The Stata Listserver


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

st: Files left open in Mata


From   "German Rodriguez" <grodri@Princeton.EDU>
To   <statalist@hsphsun2.harvard.edu>
Subject   st: Files left open in Mata
Date   Wed, 18 Oct 2006 15:53:32 -0400

I am wondering how I can clean up if a Mata function fails after opening a
file. Here is some code to demonstrate the issue

mata:
void screwup()
{
	// open a file
	ofh = fopen("locked.txt","w")
	fput(ofh,"Hi")
	// make a run time error
	a = (1,2)
	i = 3
	a[i]
	// (never) close
	fclose(ofh)
}
screwup()
end

Now screwup() will exit with error code 3301 "subscript invalid", which is
fine. The problem is that the file is still locked. Try

mata unlink("locked.txt")

and Mata will return error 3621 "attempt to write read-only file". Asking
the OS (WinXP) to delete the file doesn't work either, because the file "is
being used by another person or program", unless I exit Stata. 

This can be a problem while debugging. My workaround is to use file
locked2.txt, then locked3.txt, and so forth, until I get the code right, but
there must be a better way. 

It would be nice if Mata could automatically close open files, and perhaps
release other resources, when it abends. The alternative would be a way to
handle exceptions. Try catch finally anyone?

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



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