调用我的 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;
}