標籤:爬蟲 類 作業系統相關
在網頁爬蟲的實現過程中還涉及了一些基本的功能函數,例如擷取系統的目前時間函數,進程休眠和字串替換函數等。
我們將這些多次調用的與過程無關的函數寫成一個類Utilities。
Code:
/////Utilities.h//*************************//與作業系統相關的函數//*************************#ifndef Utilities_H#define Utilities_H#if defined(WIN32) #include <Windows.h>#else #include <sys/utime.h>#endif#include <stdio.h>#include <time.h>#include <string>#include <iostream>#include <sstream>#include <fstream>class Utilities{public:static void GetSystemTime(std::string& sdateStr,std::string& stimeStr);static void StringSearchAndReplace(std::string& sourceStr,std::string toReplace,std::string withThisStr);static bool Sleep(long lTimeMsecs);static void find_and_replace(std::string &source,const std::string find,std::string replace);static std::string replaceAll(const std::string& s,const std::string& f,const std::string& r);};#endif
//////Utilities.cpp#include "Utilities.h"void Utilities::GetSystemTime(std::string& sdateStr,std::string& stimeStr){char dateStr[9];char timeStr[9];sdateStr=_strdate(dateStr);stimeStr=_strtime(timeStr);}void Utilities::StringSearchAndReplace(std::string& sourceStr,std::string toReplace,std::string withThisStr){std::string::size_type idx=0;while(true){idx=sourceStr.find(toReplace,idx);if(idx==std::string::npos)break;sourceStr.replace(idx,toReplace.size(),withThisStr);idx+=withThisStr.length();}}bool Utilities::Sleep(long lTimeMsecs){#if defined(WIN32)::Sleep(lTimeMsecs);return (true);#elsetimeval tv;tv.tv_sec=lTimeMsecs/1000;tv.tv_usec=(lTimeMsecs%1000)*1000;if(::select(0,0,0,0,&tv)==-1)return (false);elsereturn (true);#endif}void Utilities::find_and_replace(std::string& source,const std::string find, std::string replace){size_t j;for(;(j=source.find(find))!=std::string::npos;)source.replace(j,find.length(),replace);}std::string Utilities::replaceAll(const std::string& s,const std::string& f,const std::string& r){if(s.empty()|| f.empty()|| f==r ||s.find(f)==std::string::npos)return s;std::ostringstream build_it;size_t i=0;for(size_t pos;(pos=s.find(f,i))!=std::string::npos;){build_it.write(&s[i],pos-i);build_it<<r;i=pos+f.size();}if(i!=s.size())build_it.write(&s[i],s.size()-i);return build_it.str();}
網頁爬蟲WebCrawler(2)-Utilities