c++读取hosts文件

                                                           c++读取hosts文件

    在用c++读取hosts文件时,会莫名其妙的发现第一行永远有乱码,或者告诉字“字符串不符”,并且只有第一行会这样。原因可能是编码格式不同导致的,会在每一行加一些字符什么的。只好用了个蠢方法,但凡读取到第一行就跳过,这样就不影响我下面的程序了。

  1 //读取配置文件以判断其是否配置了与VPN相关的host
  2 bool ReadHostFile()
  3 {
  4     CString strPth="C:\\Windows\\System32\\drivers\\etc\\hosts";
  5     CStdioFile sf;
  6     CFileException e;
  7     CString strSign,strFile;
  8     bool bOpen=sf.Open(strPth,CFile::typeText|CFile::modeRead,&e);
  9     if(bOpen)
 10     {
 11         //sf.Flush();
 12         int cnt=0;
 13         while(sf.ReadString(strSign)!=NULL)
 14         {
 15             cnt++;
 16             if (cnt==1) continue;  //要跳过第一次,因为第一次总是会给“字符串无效”。
 17             strFile+=strSign;
 18             strFile+="\r\n";
 19             if(strSign.Trim().GetLength()==0||strSign.GetAt(0)=='#'||strSign.GetAt(0)==';')
 20                 continue;
 21             char *row = (LPSTR)(LPCTSTR)(strSign.Trim());
 22             CString add1="vpn.oa.du.com";
 23             CString add2="vpnfreeslave.du.com";
 24             CString add3="vpnfreemaster.du.com";
 25             CString add4="vpnmon.du.com";
 26             if (strSign.Trim().Find(add1)!=-1)
 27             {
 28                 return false;
 29             }
 30             if (strSign.Trim().Find(add2)!=-1)
 31             {
 32                 return false;
 33             }
 34             if (strSign.Trim().Find(add3)!=-1)
 35             {
 36                 return false;
 37             }
 38             if (strSign.Trim().Find(add4)!=-1)
 39             {
 40                 return false;
 41             }            
 42         }
 43         sf.Close();
 44         cout<<strFile<<endl;
 45         return true;
 46     }
 47 

 

posted @ 2016-07-29 13:42  公子若不胖天下谁胖  阅读(1064)  评论(0)    收藏  举报