opening a file (and closing it later) only if flag is set
In my program I have currently a piece of code that looks like this
void foo()
{
// defining local variables
for (long i =0; i<maxiterations; i++)
{
// here the core of the code is executed
// for each iteration an object of a class is created and modified given the conditions imposed
}
if (flag) savedata();
// and here a call to the destructor of the class is called (tested, it destroys all the previously created objects)
}
Currently savedata()
is like the following
void savedata()
{
char filenameI[1024];
sprintf_s(filenameI, 1024, "%s_%i", filename, id);
FILE* File;
errno_t err;
err = fopen_s(&File, filenameI, "w");
if (err!=0)
{
cout << "\nFile" << filenameI << "could not be opened.\nPlease press Ctrl+C to terminate" << endl; // the program is run via Matlab
cin.get();
}
else
{
cout << "Saving file " << filenameI << endl;
}
for (long i =0; i<maxiterations; i++)
{
fprintf(File, "%10li", data); //not the actual line, but fprintf is used in this way
}
fclose(File);
}
Since maxiterations
is a run-time set long and given the memory required to store a single object is significant (i.e. I need higher values, but I hit the memory limit), I was thinking of modifying the code in the following way:
void foo()
{
// defining local variables
if (flag) openfile();
for (long i开发者_如何学Go =0; i<maxiterations; i++)
{
// executing the same as before
if (flag) savedata(i); // obviously the function would be modified
}
if (flag) closefile();
}
Now, finally, my question:
using the same kind of output call (a FILE* instead of a ofstream object), is it possible to achieve what I need?
My doubts arise from the fact that what's inside a loop has a scope only in that loop and thus I fear that the file could be closed when I exit the first if
statement instead of when the closefile()
is called.
Am I wrong?
Thanks to anyone who will help.
Federico
suggestion:
FILE* f = NULL;
if (flag) f = openfile();
for (long i =0; i<maxiterations; i++)
{
// executing the same as before
if (flag) savedata(i, f); // pass in filehandle, obviously the function would be modified
}
if (flag) closefile(f); //close file on handle passed.
This will eliminate extra checks:
void foo()
{
// defining local variables
if (flag)
{
openfile();
for (long i = 0; i<maxiterations; i++)
{
// executing the same as before
savedata(i); // obviously the function would be modified
}
closefile();
}
}
精彩评论