c++ ofstream没有按预期运行

C++ ofstream not operating as expected

本文关键字:运行 ofstream c++      更新时间:2023-10-16

我有一种感觉,我错过了一些明显的东西,但似乎无法解决以下问题:

请参阅下面的代码。它所做的只是循环20次,并将循环的索引写入文件。在每三次写入文件后,该文件关闭,并启动一个新文件(使用IF循环检查3次写入)。

对于第一个文件,它可以正常工作,并按预期进行写入。然后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,";
        }
    }
}

创建新文件时,在if语句中声明了第二个ofstream fsTestOutput

第二个ofstream对您的if语句具有局部作用域,因此它在if中可以正常工作。然而,当您离开if语句并返回for循环时,新的ofstream实例超出了作用域,并且您的代码恢复到使用原始实例(您已经关闭了它,因此没有输出!)

  if(test_rowcounter == 3)
  {
        test_rowcounter = 0; 
        test_filenumber++; 
        //Close the previous file and open a new one
        fsTestOutput.close();           
        sprintf(filenamebuilder, "testing_file%d",test_filenumber);
        strcat(filenamebuilder,".tsv"); 
        ofstream fsTestOutput;    // GET RID OF THIS
        fsTestOutput.open(filenamebuilder, fstream::out);
        fsTestOutput << "FILE JUST CHANGED,";
  } 

尝试删除ofstream的fsTestOutput;