删除文件中重复的行

本文以C++实现删除文件中重复的行,是作者阅读《Thinking in C++ Volume 2》中iostream章节后的练习。定义了相关常量,给出了核心函数ULISF,介绍了其参数和返回值情况,还给出了代码实现,并指出需添加相关头文件。

删除文件中重复的行

实际上是一个很简单的操作,在这里写出来是因为最近在看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>

(完)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值