删除文件中重复的行
实际上是一个很简单的操作,在这里写出来是因为最近在看Thinking in C++ Volume 2中关于iostream的章节,当作练习吧,所以写出来。J
先定义常量
const int UNIQUE_LINES_OK = 0;
const int UNIQUE_LINES_ERROR = 1;
const int FILE_OPEN_ERROR = 2;
以下函数int ULISF(const string &strFileName)即是所用到的函数,其中
参数 const string &strFileName 是 文件的名称;
返回值
UNIQUE_LINES_OK: 删除文件中重复的行执行成功;
UNIQUE_LINES_ERROR: 写入文件错误;
FILE_OPEN_ERROR: 文件打开失败。
函数如下:
int ULISF(const string &strFileName)
{
int iRet = UNIQUE_LINES_OK;
set<string> setStrLines; // the string set
string strReadLine; // temporary string read from the file
// read each lines from the file -- Begin --
ifstream fIn(strFileName.c_str()); // read the file
if(!fIn) // verify open
{
iRet = FILE_OPEN_ERROR;
return iRet;
}
while(getline(fIn,strReadLine))
{
setStrLines.insert(strReadLine);
}
fIn.close();
// read each lines from the file -- End --
// delete the file
remove(strFileName.c_str());
// write the strings of the set into the file -- Begin --
ofstream fOut(strFileName.c_str()); // write the file
if(!fOut) // verify open
{
iRet = FILE_OPEN_ERROR;
return iRet;
}
set<string>::iterator it;
for(it = setStrLines.begin(); it != setStrLines.end(); it ++)
{
fOut << it->c_str() << endl;
}
fOut.close();
// write the strings of the set into the file -- End --
return iRet;
}
由于用到C++标准库中的文件,因为还需要加上头文件
#include <iostream>
#include <string>
#include <set>
#include <fstream>
#include <iterator>
(完)