2011-08-30 40 views
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()时可能会关闭该文件。

我错了吗?

感谢任何会帮助的人。

费德里科

回答

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. 
+0

理解,谢谢。我会尽力实施它,最终我会回到你身边。 – Federico

+0

@Federico,我不明白你为什么不使用ofstream? –

+0

两个原因:1.格式化输出,我不是很实际2.不是我最初写的,我只是维护它 – Federico

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(); 
    } 
} 
+1

这不会做计算,这可能会有副作用,我们没有看到片段提供。 – RedX

+0

@RedX:谢谢你回答我的问题:D 未开发:for循环必须执行,并且不会与你的代码一起执行。 – Federico

+0

@Federico他在循环中所做的一切都是再次检查标志并调用savedata(i)。不知道与我的代码 – unexplored

相关问题