我们有三个diffrenet .cpp文件。 当我在random.cpp中创建一个文件时
ofstream outfile ("random.log");
然后我写入random.cpp文件中的random.log文件:
outfile << " something" ;
然后我去了一个不同的.cpp文件,比如StudentCS.cpp,我在那里打开文件:
ofstream outfile;
outfile.open("random.log",std::ios_base::app);
即使我在random.cpp的中间调用StudentCS,它也会在所有random.cpp输出之后写入所有StudentCS输出。我试图从random.cpp那里学习然后它调用StudentCS.cpp,它应该写一些东西然后再回到random.cpp再次写入
答案 0 :(得分:1)
打开文件一次,然后传递流对象。或者更好:使记录器对象可用于任何需要记录的模块。
答案 1 :(得分:0)
random.cpp
void studentCS(ofstream & outfile);
void random() {
ofstream outfile ("random.log");
outfile << " something" ;
outfile.close();
studentCS(outfile);
outfile.open("random.log",std::ios_base::app);
outfile << " something write after call to studenCS";
}
studentCS.cpp
void studentCS(ofstream & outfile) {
ofstream outfile("random.log",std::ios_base::app);
outfile << " something else ";
}
但请记住,您应尽量避免打开/关闭操作,因为CPU很重要。
答案 2 :(得分:0)