On Thu, 19 May 2005 13:56:37 GMT, Thomas Matthews
All depends on your style and error handling.
My preference is:
unsigned char successful = 0;
fp = fopen(...);
successful = fp == NULL;
Shirley said:
if (!successful)
{
/* File open failure */
}
if (successful)
{
successful = Process_File_Contents();
You should pass fp, otherwise it needs to be a shared "global" (at
least file-scope static, maybe more) which is yucky(tm) far beyond
this mildly clunky error handling.
Presumably the fclose() is done within Process_File_Contents(), in
which case the name is not fully descriptive, or added here ...
because now 'successful' no longer tells you accurately whether the
fopen was successful -- although fp does, it you are willing to
violate the structuring you just put so much effort into.
if (successful)
{
/* ... */
}
As for when to close a file, my opinion is to
close it as soon as you are finished with it.
Leaving a file open for longer than necessary
may allow things to happen to the internal data
{by your program or other ones).
Promptly closing a file (not opened read-only enforced by the OS) can
protect it from malfunctions in other parts of the same program --
although it would be better to fix those malfunctions anyway -- but is
very unlikely to help protect against other _programs_; indeed it may
release locks and allow _more_ access to the file by other programs.
- David.Thompson1 at worldnet.att.net