仅在设置了标志时打开文件(并在以后关闭)

时间:2011-08-30 11:37:19

标签: c++ visual-c++ fileoutputstream

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

 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()时该文件可能会被关闭被称为。

我错了吗?

感谢任何有帮助的人。

费德里科

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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();
    }
}