[英]С++ read/write file
Using C++, gcc.9x, Linux.使用 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.但是每次,在我
open
这个文件之后 - 它都会被清除。 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. 1-st:文件对象有 state。 State is updated after each operation.
State 在每次操作后更新。 You can use code like:
您可以使用如下代码:
if (!fileStreamMember_) {
// There is an error after operation
}
You can/should check state of file object during manipulations.您可以/应该在操作期间检查文件 object 的 state。
2-nd: You should close file object (or destroy it) to write all changes. 2-nd:您应该关闭文件 object(或销毁它)以写入所有更改。
std::ofstream
open()
function (and constructor) has a default flag of trunc
. std::ofstream
open()
function (和构造函数)具有默认标志trunc
。 You should specify the flags/mode parameter explicitly or use std::fstream
instead.您应该明确指定 flags/mode 参数或使用
std::fstream
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.