C++流:始终写在第 1 行

C++ ofstream : Always write onthe 1st line

本文关键字:C++      更新时间:2023-10-16

我想知道我怎么能总是写到文件的第一行。我有数字可以通过文本文件共享给另一个软文件,我想定期将这些数字写在第一行。

谢谢。

电光

如果你想完全重写文件,丢弃它的内容,那么只需使用trunc模式。但是,如果要保留任何其他内容,最简单的方法是将文件读入内存,更改第一行并写回所有内容。我认为除非您覆盖相同数量的字符,否则不可能直接更改第一行。

看看这两个函数:

ostream& seekp ( streampos pos );ostream&seekp ( streamoff off, ios_bas:seekdir dir );

也许这可以解决你的问题

 ofstream out("foo.txt");
 out << "foo";
 out << "r" << "bar";

这将留下一个只有 bar 的文件。

第二种方法:如果文件只包含一行,您可以使用ofstream::trunc打开它,并在每次写入后关闭它

如果文件不是很大,那么您可以跨每行(自定义第一行除外)编写一个新的新文件。然后更换原件。

void ReplaceFirstLine(string filename)
{
ifstream infile;
ofstream outfile;
infile.open(filename.c_str(), ios_base::in);
outfile.open("tempname.txt", ios_base::out);
bool first = true;
string s;
while (getline(infile, s, 'n'))
    {
    if (first)
        outfile << "my new first linen";
    else
        outfile << s << endl;
    first = false;
    }
infile.close();
outfile.close();
::CopyFileA("tempname.txt", filename.c_str(), FALSE); // or Linux equivalent
}
相关文章:
  • 没有找到相关文章