如何编写C++程序以在行数> 30 时擦除文本文件
How to write a C++ program to erase text file when number of lines is > 30
该程序将某些内容打印到文本文件中。当行数超过 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 重置指向文件开头的指针。这不会删除文件的内容,但会被覆盖。
相关文章:
- 引用一个已擦除类型(void*)的指针
- 擦除while循环中迭代的元素
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- C++擦除(如果存在)
- 在映射擦除c++期间执行循环的次数
- 为什么擦除方法会影响结束方法
- C++ 字符串类擦除成员函数的时空复杂性
- 类型擦除的std::function与虚拟函数调用的开销
- C++14 中unordered_map矢量和擦除删除成语的奇怪行为
- C++ 擦除函数中需要澄清
- 循环挂起迭代的 std::擦除 on std::list
- 擦除许多矢量元素,同时使用'auto'
- 如何擦除冗余输入?
- C++ STL 设置按值擦除
- 如何在C++中允许成员函数的自定义返回类型进行类型擦除?
- 为什么我的向量::擦除调用会抛出"vector subscript out of range"?
- 如何在写入文件时擦除最后一个逗号
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 双链表的擦除值函数,未知错误
- 如何编写用于多映射插入和擦除功能的 API?