Re: Reuse of FILE Variable
On Saturday, August 18, 2012 6:25:21 PM UTC-5, Mike Copeland wrote:
I'm curious about the best way to handle a file which is opened and
closed repeatedly throughout a program's execution. A file (FILE *pfv1)=
is used to write one or more different files during the program's
execution, and it can be opened and closed many times - with different
file names.
I suggest not using FILE as it has a bad design. Use std::basic_[i|o]fstrea=
m or the file classes found in many general-purpose C++ classes. The most i=
mportant thing in these classes is polymorphic streams.
My question involves the advisability of setting the file variable to=
NULL each time it's closed, as well as using that condition to dictate
subsequent open processing. My guess is that doing so will proliferate=
multiple instances of the file structure as each open is executed (and
wasting runtime memory), whereas _not_ assigning it a NULL address will=
reuse the structure during the multiple opens (for a different file's
processing). Is this true?
No. Closing a file will release the memory used for it and make it availabl=
e for subsequent allocations. You will reassign the FILE* variable anyway e=
verytime you open a file:
FILE* file = fopen("1.dat");
// use file
fclose(file);
file = fopen("2.dat"); // re-assignment
// use file
fclose(file);
So assigning NULL after closing is simply a matter of whether you need to t=
est if the file is open (which you said you did).
With std::basic_[i|o]fstream, you wouldn't use a pointer but a direct objec=
t. You can do multiple open/close sequences with the same object, and you c=
an test whether it is open with the is_open method:
wfstream file;
file.open(L"1.dat");
// use file
file.close();
// ...
if (!file.is_open())
{
file.open(L"2.dat");
// use file
file.close();
}
Note that each open/write/close sequence is discrete and file-
specific. During processing the program may well detect that the output=
file exists and will offer the user option of appending to or
overwriting the file's content.
In summary, I want to be able to use a single file multiple times for=
writing content to different files, because the logic to write data is
not specific to the output file(s) being produced.
That's not really possible, but it doesn't mean that you'll waste memory, h=
ave memory leaks, or anything like that. (With std::basic_[i|o]fstream, you=
WILL use the same file object multiple times, but the underlying OS file o=
bject/descriptor will be re-allocated for each new file you open.)
Please advise. TIA