从不同的 CPP 文件写入输出文件
writing to a output file from diffrent cpp files
我们有三个不同的.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
.cppvoid studentCS(ofstream & outfile) {
ofstream outfile("random.log",std::ios_base::app);
outfile << " something else ";
}
但请记住,您应该尽量避免打开/关闭操作,这些操作对 CPU 占用很大。
我看到你使用的是"random.log"这个名字。
这是否意味着您正在编写日志文件?如果是这样,您可以考虑使用为简化此过程而开发的众多日志记录类之一(请参阅 1、2、3、4、5)。
另一个想法...
您正在项目的不同部分打开和关闭文件。其他答案建议传递文件指针。但是,如果您确实需要从任何地方写入此文件并采取适当的预防措施,则可以考虑在此处使用全局变量。
相关文章:
- 如何在 的开头<x>和结尾<y>之间更改带有文件输出的字符串的值
- C++对象数组的文件输出
- bcdedit 文件输出不起作用,但其他命令可以
- 如何从文本文件输出数据?(学生成绩单计划)
- 使用 C++文件 I/O 输出 pdf 文件
- C 文件输出垃圾
- 从堆栈中读取字符后,如何修复不正确的文件输出
- C++:具有随机名称的文件输出
- 在命令提示符下看到换行符,但在文件输出中可以看到 相同的字符串
- 生成文件不会生成预期的文件输出
- C++11 fgetc 在"r+b"模式下使用时向我的文件输出 0
- 使用函数从文件输出
- GCC.obj文件输出不具有确定性(.debug_info,PROGPITS部分)
- C cstdiofile :: Writestring给出了不正确的文件输出
- C 输出:STD :: COUT和文件输出没有相同的内容
- GCC和MSVC之间的文件输出不一致
- C++文件输出奇怪的数字,并且部分代码没有运行
- 如何将特定字符从TXT文件输出到特定点
- C 调用从TXT文件输出信息的函数
- 将交易从文本文件输出到屏幕