我有一种感觉,我遗漏了一些明显的东西,但似乎无法解决以下问题:
请看下面的代码。它所做的只是循环 20 次并将循环的索引写入文件。每 3 次写入文件后,该文件关闭并启动一个新文件(使用 IF 循环检查 3 次写入。
它适用于第一个文件并按预期写入。然后 IF 第一次启动并关闭当前文件并启动新文件。
注意:此时我可以很好地写入新文件。
然后 IF 结束并将处理返回到 FOR 循环。但是现在写入文件不起作用(没有错误,没有写入)。
因此,该文件在创建它的 IF 块中成功写入。然后 IF 块结束。然后 FOR 循环结束当前的 pass 并开始一个新的 pass。现在写不出来了。
任何人都可以帮忙,我可以找到方法来做我需要做的不同的事情,但我只是想了解为什么会这样?
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,";
}
}
}