调用我的write函数时,编译器会看到文件需要保持打开状态,对吧?或者每次调用函数时都会打开和关闭文件?另外,即使没有明确关闭,我的文件也会在最后关闭吗? 这是处理写入同一文件的最佳方法吗?
void write(const std::string &filename, const std::string &text)
{
std::ofstream file(filename, std::ios_base::out | std::ios_base::app );
file << text << std::endl;
}
void write2(std::ofstream &file, const std::string &text)
{
file << text << std::endl;
}
int main(int argc, char** argv)
{
int count(0);
for (int i=0; i<10; ++i)
{
// Do heavy computing ...
++count;
std::ostringstream out; out << count;
write("test", out.str());
}
// Alternative
std::ofstream file("test", std::ios_base::out | std::ios_base::app );
count = 0;
for (int i=0; i<10; ++i)
{
// Do heavy computing ...
++count;
std::ostringstream out; out << count;
write2(file, out.str());
}
return 0;
}
答案 0 :(得分:3)
std::ofstream file
将在其析构函数中关闭,位于write
的末尾(如果它通过异常退出,则会更早)。因此,文件将在循环的每次迭代中打开和关闭。
http://en.cppreference.com/w/cpp/io/basic_ofstream
也许您可以创建一个包含该文件的小包装类,并且具有write
成员函数,或者更改write
以获取您在循环上方创建的std::ofstream&