There are potential issues either way. Opening and closing a file frequently is going to put extra load on the file system; since it is optimized for lots of writes, not for frequent reopening (and each time you close the file it will have to flush the pending writes). On the other hand, an open file has a greater potential for corruption (eg during a power failure). Both of these are only issues when taken to the extreme (thousands of file closes vs keeping it open for hours at a time). So most people would err on the side of keeping the file open because the code is simpler (especially since newer file systems cope quite well with sudden outages).
The other code consideration is localization of use; open the file only in the section/module/class that needs it, and close it when it has been used. This will localize the effect of any code changes.
Last edited by neonsignal; 05-24-2011 at 10:33 PM.
|