私のプログラムには現在、次のようなコードがあります
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
ランタイム セットが長く、1 つのオブジェクトを格納するために必要なメモリが大きい (つまり、より高い値が必要ですが、メモリ制限に達した) ことを考えると、次のようにコードを変更することを考えていました。
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();
}
さて、最後に、私の質問:
同じ種類の出力呼び出し (ofstream オブジェクトの代わりに FILE*) を使用して、必要なものを達成することは可能ですか?
私の疑問は、ループ内にあるものがそのループ内にのみスコープを持っているという事実から生じるためif
、が呼び出されたときではなく、最初のステートメントを終了したときにファイルが閉じられるのではないかと心配していますclosefile()
。
私が間違っている?
助けてくれる人に感謝します。
フェデリコ