如何编写C++程序以在行数> 30 时擦除文本文件

How to write a C++ program to erase text file when number of lines is > 30

本文关键字:gt 擦除 文件 文本 C++ 何编写 程序      更新时间:2023-10-16

该程序将某些内容打印到文本文件中。当行数超过 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 重置指向文件开头的指针。这不会删除文件的内容,但会被覆盖。