Using C++, gcc.9x, Linux. I try to open and read file and then keep it opened for further operation - rewrite it for each iteration. But each time, after I do open
this file - it gets wiped out. Is it possible to keep file content until I rewrite it? And I want to keep file opened for writing all the time.
constructor()
{
{
ifstream tmp("file.db");
int date;
tmp >> date;
}
// it gets wiped out here, but I don't want it.
// And I want to keep ofstream opened all the time.
fileStreamMember_.open("file.db"); // std::ofstream
}
writeMethod()
{
fileStreamMember_.seekp(0, ios::beg);
fileStreamMember_<< date_ << endl;
}
1-st: File objects have state. State is updated after each operation. You can use code like:
if (!fileStreamMember_) {
// There is an error after operation
}
You can/should check state of file object during manipulations.
2-nd: You should close file object (or destroy it) to write all changes.
std::ofstream
open()
function (and constructor) has a default flag of trunc
. You should specify the flags/mode parameter explicitly or use std::fstream
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.