0

在我的程序中,我目前有一段看起来像这样的代码

 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()调用时,文件可能会关闭。

我错了吗?

感谢任何会提供帮助的人。

费德里科

4

2 回答 2

1

建议:

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.
于 2011-08-30T11:53:31.123 回答
0

这将消除额外的检查:

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();
    }
}
于 2011-08-30T12:48:58.503 回答