C++中如何删除txt文件中指定的一行

如题所述

两种方式:
1、一次性全部读取到字符串列表,修改后再保存为新文件(也就是覆盖以前的文件)
2、依次读取每一行,并输出到新文件,需要被删除的那一行不输出就行了。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-21
保存在字符串数组内,每一个元素保存一行,删除这行,然后把数组重新覆盖在文件中就行了。覆盖的时候忽略掉被删掉的这行。本回答被提问者采纳
第2个回答  2015-08-13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

#include <fstream>
#include <string>

using namespace std;

int main()
{
vector<string> vecContent;
string strLine;
ifstream inFile("e:\\test.txt");
while (inFile)
{
getline(inFile, strLine);
vecContent.push_back(strLine);
}
inFile.close();

// 删除第一行
vecContent.erase(vecContent.begin());

ofstream outFile("e:\\test.txt");
vector<string>::const_iterator iter = vecContent.begin();
for (; vecContent.end() != iter; ++iter)
{
outFile.write((*iter).c_str(), (*iter).size());
outFile << '\n';
}

outFile.close();

return 0;
}
相似回答