该程序将某些内容打印到文本文件中。当行数超过 30 行时,我想擦除文本文件的内容,然后它应该再次开始在文本文件内打印。
void GPSCallback(const gps_common::GPSFix::ConstPtr& msg)
{
std::ofstream output;
output.open("file1.txt",std::ios_base::app);
output<<"n"<<msg->latitude<<","<<msg->longitude;
output.close();
usleep(10000000);
}
可以使用计数器,例如在调用GPSCallback
的函数中跟随
if(++count < 30)
GPSCallback(msg);
else{
count =0;
std::ofstream output;
output.open("file1.txt");
output.close();
GPSCallback(msg);
}
试试这个
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int count=0;
output.open("file1.txt",std::ios_base::app);
if (output.is_open()) {
while (!output.eof()) {
getline(name);
count++;
}
}
if(count>=30)
{
// do whatever you want
}
output.close();
}
一旦达到 30 行限制,就可以使用 seekp 重置指向文件开头的指针。这不会删除文件的内容,但会被覆盖。