c++ ofstream没有按预期运行
C++ ofstream not operating as expected
我有一种感觉,我错过了一些明显的东西,但似乎无法解决以下问题:
请参阅下面的代码。它所做的只是循环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;
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- 如何通过cpp程序运行shell脚本
- IPC使用多个管道和分支进程来运行Python程序
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在C应用程序中运行C++(带有STL)函数
- 传递数组结构、ofstream 和 interger 以运行
- 当使用CMake使用CLion运行时,ofstream不会创建文件
- c++ ofstream没有按预期运行