所以我必须为一项作业制作银行计划,而我的教授想要一个每个“操作”的日志文件(他对此非常模糊,我决定记录输入和输出)。我遇到的问题是,每当我调用一个新函数时,我必须重新打开该文件并覆盖以前的文件。据我所知,重复使用.open将导致我所处的任何功能忽略先前的输出 我试图宣布一个全球性的流程,希望它会改变,但问题仍然存在。刷新和/或关闭似乎没有帮助,但完全有可能我滥用它们或语法错误。下面的代码是主要功能,read_accts功能和菜单功能。如果我在调用read_accts函数之前终止程序,日志文件将有“有多少个帐户?”但是如果我允许程序调用另外两个函数,那么日志文件只有菜单文件的输出。我为长篇大论道歉,但我对于出了什么问题感到茫然。
{{1}}
答案 0 :(得分:0)
据我所知,默认情况下,ofstream将以std :: fstream :: out模式打开文件,如果将删除现有文件或创建新文件。
将其更改为std :: fstream :: app http://www.cplusplus.com/reference/fstream/fstream/open/
编辑: 好像你只使用两个ostream到一个文件。它无法拒绝访问Using std:fstream how to deny access (read and write) to the file
将ostream传递给被调用的函数
int read_accts(BankAccount account[],int MAX_NUM,int &num_accts, ostream& log)
{
log.open("log.txt",std::ofstream::app); // remove this line since you already open it in main()
在主要
中调用它read_accts(account,MAX_NUM,num_accts, log);
答案 1 :(得分:0)
我认为你唯一的问题是你必须在写入文件之前添加它。
log.seekp(0, std::ios_base::end);
这会将文件指针设置为文件末尾并继续从那里写入。
您的文件已在int main ()
中打开,如果将变量log
传递给函数int read_accts(BankAccount account[], int MAX_NUM, int &num_accts)
会更好
并使其成为int read_accts(BankAccount account[], int MAX_NUM, int &num_accts, ofstream log );
并定义
int read_accts(BankAccount account[], int MAX_NUM, int &num_accts, ofstream log )
{
string f;
string l;
int social;
int acct;
string type;
double bal;
int i = 0;
ifstream readfile;
readfile.open("bankdatain.txt");
if (!readfile)
{
cout << "Can't open input file." << endl;
log << "Can't open input file." << endl;
exit(1);
}
while (readfile >> f >> l >> social >> acct >> type >> bal)
{
account[i].setfname(f);
account[i].setlname(l);
account[i].setssnum(social);
account[i].setacctnum(acct);
account[i].settype(type);
account[i].setbalance(bal);
i++;
num_accts++;
}
return num_accts;
}
seekp()
的PS 语法为
ostream& seekp (streampos pos);
ostream& seekp (streamoff off, ios_base::seekdir way);
参考here
PS 等同于ifstream
的{{1}}