fstream的用法+代码

写文件:

 CString szFilter1 = _T("导出路径文件(*.txt)|*.txt;|所有文件(*.*)|*.*||");
    
 CFileDialog dlg(FALSE, _T(".txt"), NULL, OFN_CREATEPROMPT|OFN_OVERWRITEPROMPT,szFilter1);

 if (dlg.DoModal()==IDOK)
 {
  CComBSTR str=dlg.GetPathName();
   
  std::ofstream cout;
  cout.open(str, std::ios::out);  // 如果文件不存在可自动创建之
  if (cout)
  {
   for (long i = 0; i < nodeCnt; i++)
   {
    pLineCurve->GetNode(i,&pNode);
    pNode->GetXYZ(&x,&y,&z);
    cout<<x<<','<<y<<','<<z<<std::endl;    
   }
   cout.close();
  }
 }

读文件:

CString szFilter1 = _T("导入路径文件(*.txt)|*.txt;|所有文件(*.*)|*.*||");
       
 CFileDialog dlg(TRUE, _T(".txt"), NULL, OFN_READONLY|OFN_FILEMUSTEXIST,szFilter1);

 if (dlg.DoModal()==IDOK)
 {
  CComBSTR str=dlg.GetPathName();
  
  //char *buff = _com_util::ConvertBSTRToString(str);
  std::fstream cin(str,std::ios::in);
  if (cin)
  {
   double x,y,z;
   IGLineCurvePtr pLineCurve=NULL;
   IGNodePtr pNode=NULL;
   CoCreateInstance(__uuidof(GLineCurve),NULL,CLSCTX_INPROC_SERVER,IID_IGLineCurve,(void**)&pLineCurve);
   char a;
   //1. 判断文件是否为空时使用peek函数,若peek返回EOF则文件为空;
   //2. 读取文件过程中,读取非char型时,使用peek判断文件尾将不再适用,循环判断条件应改用>>操作符进行读取,若读入char型缓冲区,peek函数会表现得很好。
   while (!cin.eof())
   {
    cin >> x >> a >> y >> a >> z;
    CoCreateInstance(__uuidof(GNode),NULL,CLSCTX_INPROC_SERVER,IID_IGNode,(void**)&pNode);
    pNode->PutXYZ(x,y,z);
    pLineCurve->AddNode(pNode);
   }
   cin.close();   
   // 最后一个点读入时会重复,vc7,vc8都有这个问题,删除之
   pLineCurve->RemoveNode(pNode);

   m_pCutElement->put_Geometry(pLineCurve);

   m_pSceneView->Render();

   m_NodeList.DeleteAllItems();
   //列出顶点
   CString strText;
   long lNodeCount = 0;pLineCurve->get_NodeCount(&lNodeCount);
   for(long i = 0; i < lNodeCount; ++i)
   {
    IGNodePtr node = NULL;
    pLineCurve->GetNode(i,&node);
    strText.Format(_T("%d"), i + 1);
    int nItem = m_NodeList.InsertItem(i, strText);
    if(nItem == -1)
     break;
    double lx,ly,lz;
    node->GetXYZ(&lx,&ly,&lz);
    strText.Format(_T("%.6f"), lx);
    m_NodeList.SetItemText(nItem, 1, strText);
    strText.Format(_T("%.6f"), ly);
    m_NodeList.SetItemText(nItem, 2, strText);
    strText.Format(_T("%.6f"), lz);
    m_NodeList.SetItemText(nItem, 3, strText);
   }   
  }
 }

原文地址:https://www.cnblogs.com/mazhenyu/p/2044445.html