明らかな何かが欠けているような気がしますが、次のことを解決できないようです:
以下のコードを参照してください。20 回ループし、ループのインデックスをファイルに書き込むだけです。ファイルへの 3 回の書き込みごとに、そのファイルが閉じられ、新しいファイルが開始されます (3 回の書き込みをチェックする IF ループを使用します。
最初のファイルでは問題なく動作し、期待どおりに書き込みます。次に、IF が初めて開始され、現在のファイルが閉じられ、新しいファイルが開始されます。
注: この時点で、新しいファイルに問題なく書き込むことができます。
次に、IF が終了し、処理を FOR ループに戻します。しかし、ファイルへの書き込みが機能しなくなりました (エラーも書き込みもありません)。
したがって、ファイルは、それを作成する IF ブロックに正常に書き込まれます。その後、IF ブロックが終了します。次に、FOR ループが現在のパスを終了し、新しいパスを開始します。現在、書き込みは機能しません。
別の方法で行う必要があることを行う方法を見つけることができますが、なぜこれが起こっているのかを理解したいだけですか?
int main()
{
unsigned int test_rowcounter = 0;
unsigned int test_filenumber = 0;
char filenamebuilder[50] = "";
sprintf(filenamebuilder, "testing_file%d",test_filenumber);
strcat(filenamebuilder,".tsv");
ofstream fsTestOutput;
fsTestOutput.open(filenamebuilder, fstream::out);
//Loop 20 times writibng the loop index value to a file
for(unsigned int f=0;f<20;f++)
{
fsTestOutput << f; //This write only works for the original file
test_rowcounter++;
//If three rows have been written to a file then start a new file
if(test_rowcounter == 3)
{
test_rowcounter = 0;
test_filenumber++; // increment the number that is added to the
// base filename to create a new file
//Close the previous file and open a new one
fsTestOutput.close();
sprintf(filenamebuilder, "testing_file%d",test_filenumber);
strcat(filenamebuilder,".tsv");
ofstream fsTestOutput;
fsTestOutput.open(filenamebuilder, fstream::out);
// This next line works, the data is written
// for all files at this point
fsTestOutput << "FILE JUST CHANGED,";
}
}
}