例如txt文件中
123456#注释
234567#注释
345678#注释
我需要删除234567这一整行怎么操作
最好能定时删除(多少时间之后再删除)
逐行读取,写入另一个临时文件,当都的第N行的时候,跳过这一行的写入。
写完后,删除源文件,重命名临时文件即可。
源文件:
删除第2行后的文件:
代码如下:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const char* filename = "./a.txt";
const char* tmpname = "./a_tmp.txt";
char buf[1024];
int i=0,n; //需要删除的行
ifstream ifs;
ofstream ofs;
ifs.open(filename);
if (!ifs.is_open())
{
cout << "file open error" << endl;
return 0;
}
ofs.open(tmpname);
cout << "请输入需要删除的行数:";
cin >> n;
while (!ifs.eof())
{
ifs.getline(buf, 1024,'\n');
if (i != n - 1)
ofs << buf << "\n";
i++;
}
ifs.close();
ofs.close();
//删除源文件,并重命名临时文件
remove(filename);
rename(tmpname, filename);
return 0;
}