我想知道如何始终写入文件的第一行。我有数字要通过文本文件共享给另一个软件,我想在第一行定期写下这些数字。
谢谢。
欧
如果你想完全重写文件,丢弃它的内容然后简单地使用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 line\n";
else
outfile << s << endl;
first = false;
}
infile.close();
outfile.close();
::CopyFileA("tempname.txt", filename.c_str(), FALSE); // or Linux equivalent
}
看看这两个函数:
ostream& seekp (streampos pos); ostream& seekp (streamoff off, ios_bas:seekdir dir);
也许这可以解决您的问题
ofstream out("foo.txt");
out << "foo";
out << "\r" << "bar";
这将留下一个只有 bar 的文件。
第二种方法:如果文件只包含一行,您可以ofstream::trunc
在每次写入后打开并关闭它