【发布时间】:2011-11-06 17:40:19
【问题描述】:
在我的程序中,我目前有一段看起来像这样的代码
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() 时文件可能会关闭。
我错了吗?
感谢任何愿意提供帮助的人。
费德里科
【问题讨论】:
标签: c++ visual-c++ fileoutputstream