【问题标题】:C++ ofstream : Always write onthe 1st lineC++ ofstream:总是写在第一行
【发布时间】:2012-05-18 19:15:09
【问题描述】:

我想知道如何始终写入文件的第一行。 我有数字要通过文本文件分享给另一个软件,我想在第一行定期写下这些数字。

谢谢。

eo

【问题讨论】:

  • 也许我错了,但是seekp-method 设置了一个放置指针。
  • 是替换第一行还是先插入新行?
  • @dwalter 我想换行
  • 只需使用seekp-method 将 put-pointer 设置为零位置。
  • 如果可能的话,使用另一种方法进行进程间通信((命名的)管道、共享内存、套接字等)。

标签: c++ io overwrite


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    看看这两个函数:

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

    【讨论】:

      【解决方案3】:

      也许这能解决你的问题

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

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

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

      【讨论】:

        【解决方案4】:

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

        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 line\n";
            else
                outfile << s << endl;
            first = false;
            }
        
        infile.close();
        outfile.close();
        ::CopyFileA("tempname.txt", filename.c_str(), FALSE); // or Linux equivalent
        }
        

        【讨论】:

          猜你喜欢
          • 2013-02-16
          • 1970-01-01
          • 1970-01-01
          • 2012-04-27
          • 1970-01-01
          • 2012-04-15
          • 1970-01-01
          • 2021-08-13
          • 2012-03-31
          相关资源
          最近更新 更多