这几天一直在解决座位号重复问题,所以考虑到用文件读写来判断字符串是否重复。
刚开始是使用固定的长度来写入文件和替换字符串,但是考虑到代码的复用性,后来还是修改了任意字符串的读写和替换,方便以后使用。
1:添加字符串到文件:
函数原型:bool AddSeatID(char *_setNum,int length);
函数实现:
bool CFileTest::AddSeatID(char *_setNum,int length)
{
if (checkDuplicate(_setNum))
{
return false;
}
if (!openFile("ab+"))
{
printf("open file failed \n");
return false;
}
char seatBuf[length+4];
memset(seatBuf,0,length+4);
memcpy(seatBuf,"[",1);
memcpy(seatBuf+1,_setNum,length);
memcpy(seatBuf+length+1,"]\r\n",3);
fseek(m_fp,0L,SEEK_END);
fwrite(seatBuf,length+4,1,m_fp);
closeFile();
m_seatIDList.push_back(_setNum);
return true;
}
已追加方式写入文件,其中有使用判断字符串是否存在于文件中,如果有存在则返回false,不存在则写入文件。其中设置m_seatIDList为vector容器,将字符串保存到内存中
2:字符串重复判断函数:
函数原型:bool checkDuplicate(char* _seatID);
函数实现:
bool CFileTest::checkDuplicate(char* _seatID)
{
string seatID;
if (m_seatIDList.empty())
{
return false;
}
vector<string>::iterator iter;
vector<string>::iterator beginVec = m_seatIDList.begin();
vector<string>::iterator endVec = m_seatIDList.end();
for (iter = beginVec; iter!= endVec; iter++)
{
if (!strcmp(iter->c_str(),_seatID))
{
return true;
}
}
return false;
}
将需要判断重复的字符串传入,并将此字符串与文件中读出的字符串进行比较
3:替换新旧字符串函数:
函数原型:bool changeSeatID(char* _oldSeat,int _oldLength,char* _newSeat,int _newLength);
函数实现: