从不同的 CPP 文件写入输出文件

writing to a output file from diffrent cpp files

本文关键字:文件 输出 CPP      更新时间:2023-10-16

我们有三个不同的.cpp文件。当我随机制作文件时.cpp

    ofstream outfile ("random.log");

然后我写入文件随机.log在随机.cpp文件中:

    outfile << " something" ;

然后我转到另一个.cpp文件,如 StudentCS.cpp在那里我使用以下方法打开文件:

    ofstream outfile;
    outfile.open("random.log",std::ios_base::app);

它将在所有随机输出之后写入所有 StudentCS 输出.cpp即使我在 random.cpp 中间调用 StudentCS。我正在尝试从随机开始.cpp然后它调用 StudentCS.cpp它应该写一些东西然后回到随机.cpp它再次写入

打开文件一次,然后传递流对象。或者更好:使记录器对象可用于任何需要日志记录的模块。

随机.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";
}

学生CS

.cpp
void studentCS(ofstream & outfile) {
   ofstream outfile("random.log",std::ios_base::app);
   outfile << " something else ";
}

但请记住,您应该尽量避免打开/关闭操作,这些操作对 CPU 占用很大。

我看到你使用的是"random.log"这个名字。

这是否意味着您正在编写日志文件?如果是这样,您可以考虑使用为简化此过程而开发的众多日志记录类之一(请参阅 1、2、3、4、5)。

另一个想法...

您正在项目的不同部分打开和关闭文件。其他答案建议传递文件指针。但是,如果您确实需要从任何地方写入此文件并采取适当的预防措施,则可以考虑在此处使用全局变量。