简体   繁体   English

c ++:将ofstream&传递给函数以连续追加到.txt文件

[英]c++ : passing ofstream& to function to continually append to .txt file

I am writing a program for class wherein I need to call a function multiple times from "main.cpp" which takes an ofstream as a parameter, and the function itself needs to append new data to the end of the .txt file every time it's called (in this example I've made the data of type int for simplicity's sake). 我正在为类编写程序,其中我需要从“ main.cpp”中多次调用一个函数,该函数以ofstream作为参数,并且函数本身每次都需要向.txt文件的末尾追加新数据。称为(在此示例中,为简单起见,我将数据类型设置为int)。

What's been happening is that when the function gets called multiple times in main, it just overwrites everything instead of appending new data to the end of the file. 发生的事情是,当函数在main中多次调用时,它只会覆盖所有内容,而不是将新数据附加到文件末尾。 I know everything else in my program works so I'm just going to strip it down to the bare bones as much as possible so that this isn't TL;DR. 我知道程序中的所有其他内容都可以正常工作,所以我将尽可能地将其剥离到最底层,以免不是TL; DR。 I have included 我已经包括

#include<fstream>
using namespace std;

in all of my files. 在我所有的文件中

Here's the gist of it: 这是要点:

in main.cpp: 在main.cpp中:

aClass* someClass = new aClass;
int data = 0;
...
ofstream myfile ("file.txt");
someClass->appendData(myfile, data);
...

in aClass.h: 在aClass.h中:

void appendData(ofstream& myfile, int data);

in aClass.cpp: 在aClass.cpp中:

void aClass::appendData(ofstream& myfile, int data){
    if(myfile.is_open()){
        myfile << data << "\n";
        myfile.close();
    }
    else cout << "Couldn't open file";
}

If anyone could help me with this I'd appreciate it. 如果有人可以帮助我,我将不胜感激。 For some reason they haven't had us touch fstreams in over a year and I'm not sure what the problem is here. 由于某些原因,他们一年多来没有让我们接触fstreams,我不确定这是什么问题。

The call 通话

myfile.close();

in appendData is not right. appendData中不正确。 Any subsequent output operations on myfile are ignored. myfile上的任何后续输出操作都将被忽略。

Remove it from there. 从那里删除它。

You may add it in main but it is optional. 您可以在main添加它,但是它是可选的。 The destructor will call close() . 析构函数将调用close() However, there is no harm if you call close() on the object if you are sure you are not going to use it to write into it any more 但是,如果您确定不再使用该对象写入对象,则对对象调用close()不会有任何危害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM