1. 程式人生 > >C++fstream,ifstream和outstream讀取檔案最後一行注意

C++fstream,ifstream和outstream讀取檔案最後一行注意

char cntext[1024] = {0};
 fstream cnText("E:\\Work\\Diagnose\\Chrysler\\BAIC\\CN_TEXT.txt");
 //cnText.open(("E:\\Work\\Diagnose\\Chrysler\\BAIC\\CN_TEXT.txt"));
 ofstream outFile("E:\\Work\\Diagnose\\usa\\Chrysler\\LIBTEXT\\cn_text.txt");
 if (!cnText.is_open())
  return;
 if (!outFile)
  return;
 while (!cnText.eof())
 {
  char chBuf[20] = { 0 };
  cnText.getline(cntext, sizeof(cntext));
  CString cnStr(cntext);

//這裡會把最後一行空行都進來,然後在下一次結束while迴圈,所以這裡需要做判空處理否則可能會出錯
  if (cnStr.IsEmpty())
   break;


  CString id = cnStr.Left(cnStr.Find("="));
  CString value = cnStr.Mid(cnStr.Find("=")+1, cnStr.GetLength()- cnStr.Find("=")-1);
  if (value.IsEmpty())
  {
   sprintf(chBuf, "%.12x", atoi(id.GetBuffer()));
   string strValue = chBuf;
   CoverCap(strValue);
   Cover0x(strValue);
   string out = strValue + "\t\t" + "";
   outFile << out;
   outFile << "\n";
   continue;
  }
  sprintf(chBuf, "%.12x", atoi(id.GetBuffer()));
  string strValue = chBuf;
  CoverCap(strValue);
  Cover0x(strValue);
  string out = strValue + "\t\t" + "\"" + value.GetBuffer() + "\"";
  outFile << out;
  outFile << "\n";
 }
 cnText.close();
 outFile.close();