在我的程序中,我目前有一段看起来像这样的代码
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)
}
目前savedata()
是这样的
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);
}
由于maxiterations
运行时设置很长并且考虑到存储单个对象所需的内存很重要(即我需要更高的值,但我达到了内存限制),我正在考虑通过以下方式修改代码:
void foo()
{
// defining local variables
if (flag) openfile();
for (long i =0; i<maxiterations; i++)
{
// executing the same as before
if (flag) savedata(i); // obviously the function would be modified
}
if (flag) closefile();
}
现在,最后,我的问题:
使用相同类型的输出调用(一个 FILE* 而不是一个 ofstream 对象),是否有可能实现我所需要的?
我的怀疑源于循环内的内容仅在该循环中具有范围,因此我担心当我退出第一个if
语句而不是closefile()
调用时,文件可能会关闭。
我错了吗?
感谢任何会提供帮助的人。
费德里科