在我的节目,我有当前一段代码,看起来像这样打开一个文件(以后将其关闭)仅当标志设置
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()
时可能会关闭该文件。
我错了吗?
感谢任何会帮助的人。
费德里科
理解,谢谢。我会尽力实施它,最终我会回到你身边。 – Federico
@Federico,我不明白你为什么不使用ofstream? –
两个原因:1.格式化输出,我不是很实际2.不是我最初写的,我只是维护它 – Federico