c++文件常见操作示例

 
C++ 常见文件操作示例
1.       复制文件:
    UpdateData ();
     // 提示用户是否复制文件
     if (MessageBox(" 是否将原始文件复制到目标文件?","提示",MB_OKCANCEL)==IDOK)
     {    CFile *pSrcFile=NULLCFile *pDstFile=NULL;// 定义两个指向原始文件和目标文件的指针
         TRY
         {    pSrcFile=new CFile(m_szSrcFile, CFile::modeRead); // 原始文件赋值给指针
              pDstFile=new CFile(m_szDrcFile, CFile::modeCreate|CFile::modeWrite);// 目标文件            int nRead;    // 读取的字节数
              char szBuffer[1024];   // 复制缓冲区,用于将读取的数据缓存,然后写入
              // 循环直到读取的字节数为0
             while (nRead=pSrcFile->Read(szBuffer,sizeof(szBuffer)))
            {       pDstFile->Write(szBuffer,nRead);            }
              pSrcFile->Close();          pDstFile->Close();// 关闭文件指针
              delete pSrcFile;            delete pDstFile;// 删除,否则内存泄漏
              MessageBox(" 文件复制成功。","提示",MB_OK); //提示复制成功
         }
         CATCH(CFileException,e)
         {   MessageBox(" 文件复制失败。","提示",MB_OK); //出错,提示复制失败
              if (pSrcFile!=NULL)
              {    pSrcFile->Abort(); delete pSrcFile; // 安全关闭原始文件
              }
              if (pDstFile!=NULL)
              {    pDstFile->Abort(); delete pDstFile;
              }
         }
         END_CATCH
     }   
2.       剪切文件内容(从A文件把内容剪切到B文件,并删除A文件,AB两文件类型相同)
     UpdateData();
     // 提示用户是否移动文件
     if (MessageBox(" 是否将原始文件移动到目标文件?","提示",MB_OKCANCEL)==IDOK)
     {    CFile *pSrcFile=NULL;       CFile *pDstFile=NULL;
         TRY
         {    pSrcFile=new CFile(m_szSrcFile, CFile::modeRead); // 原始文件
              pDstFile=new CFile(m_szDrcFile, CFile::modeCreate|CFile::modeWrite);// 目标文件
              int nRead;    // 读取的字节数
              char szBuffer[1024];   // 复制缓冲区,用于将读取的数据缓存,然后写入
              // 循环直到读取的字节数为0
              while (nRead=pSrcFile->Read(szBuffer,sizeof(szBuffer)))
              {             pDstFile->Write(szBuffer,nRead);
              }
         pSrcFile->Close();          pDstFile->Close();
              delete pSrcFile;            delete pDstFile;
              CFile::Remove(m_szSrcFile); // 删除原文件
              MessageBox(" 文件移动成功。","提示",MB_OK); //提示移动成功
         }
         CATCH(CFileException,e)
         {    MessageBox(" 文件移动失败。","提示",MB_OK); //出错,提示移动失败
              if (pSrcFile!=NULL)
              {    pSrcFile->Abort();               delete pSrcFile;
              }
              if (pDstFile!=NULL)
              {    pDstFile->Abort();               delete pDstFile;
              }
         }
         END_CATCH
     }
3.       删除文件( CFile ::Remove(m_szSrcFile) 见上例)
4.       创建文件
TRY
     {    //creatfilename.txt 为所要创建的文件
CFile file=new CFile("creatfilename.txt",CFile::modeCreate|CFile::modeWrite);
         AfxMessageBox("creatfilename.txt 文件创建成功",MB_OK);
     }
     CATCH(CFileException,e)
     {        TRACE("Error=%u",e->m_cause);    }
     END_CATCH
     }
5.       读取文件
     iniDir=strPath;// 文件路径:如C:D/test.txt
     CStdioFile iniConfigFile;
     if(iniConfigFile.m_pStream=fopen(iniDir,"r+w"))// 打开文件
     {    int pass[3]={0};// 每班合格人数        int total[3]={0};// 每班总人数
         while(!feof(iniConfigFile.m_pStream))// 判断文件是否是末尾
         {    char buf[1024];// 定义缓冲数组存储读取的值
              LPTSTR temp=iniConfigFile.ReadString(buf,1024);// 读第一行并将值存储到缓冲数组
              CString strSrc = temp;// 将指向第一行的指针赋值给strSrc
              // 去掉该行的左右两端空格,回车符,跳格符
              strSrc.TrimLeft(" ");           strSrc.TrimRight(" ");
              strSrc.TrimRight(" ");           strSrc.TrimRight(" ");
              strSrc.TrimRight("/t");          strSrc.TrimRight("/n ");
              int pos;// 该行分隔符的位置
              // 可以用for语句改写
              CString studentInfo[5];// 用来存储第一行的以逗号做为分隔符的值
              for(int i=0;i<4;i++)
              {    pos=strSrc.FindOneOf(",");
                   studentInfo[i]=strSrc.Left(pos);
                   strSrc=strSrc.Right(strSrc.GetLength()-pos-1);
              }
              studentInfo[4]=strSrc;
// 以下是对读取到的数据进行处理,好写在数据库中,不是本处的重点,详细代码,参考DataTODataBase的源码
// 以下三行代码是将CString类型转换为整型的代码
                   char * pchar2=studentInfo[4].GetBuffer(studentInfo[4].GetLength());
                   int iscore=atoi(pchar2);
                   if(iscore>=60) pass[0]++;
              }
     }
else
     {
         CString err;
         err.Format(" 找不到文件:%S /n",iniDir);
         AfxMessageBox(err,MB_ICONSTOP);
     }
     iniConfigFile.Close();
     // 为了避免重复转换最好导入后将原始数据删除
    remove(iniDir);
6.       写文件
     CString classid[3]={"class1","class2","class3"};
         float yield[3]={0.0};// 班级合格率
         for(int i=0;i<3;i++)
         {    yield[i]=float(pass[i])/float(total[i]);
              WriteTotalToDataBase(classid[i],total[i],pass[i],yield[i]);
// 该函数是将每个班的总信息写入到classTotal表中
         }
         // 用C语言写入到classTotal.txt中,
         string filename="classTotal.txt";
         FILE * fh;
         fh = fopen(filename.c_str(), "wb");
         if(fh == NULL) {   AfxMessageBox(" 被写入的文件打开失败",MB_OK);   }
         CString total_str[3],pass_str[3],yield_str[3];
         for(int i=0;i<3;i++)
         {    // 以下三句是把int型转化为CString型
total_str [i].Format("%d",total[i]);       pass_str[i].Format("%d",pass[i]);
              yield_str[i].Format("%f",yield[i]);
         }
        for(int i=0;i<3;i++)
         {// 定义以个string类型用来连接以上信息值
string filecontents=classid[i] + "," +total_str[i] + "," +pass_str[i] + "," +yield_str[i]+ "/t";
         fprintf(fh,filecontents.c_str());// 将信息写入fh
         }
          AfxMessageBox(" 数据成功写入classTotal.txt",MB_OK);
         if(fclose(fh) != 0)
         {        AfxMessageBox(" 被写入的文件关闭失败",MB_OK);       }
       // 用C++语言写入到classTotal1.txt中
         CStdioFile mFile;
         CFileException mExcept;
         mFile.Open( "classTotal1.txt", CFile::modeWrite, &mExcept);
         CString filecontents1;
         for(int i=0;i<3;i++)
         {
      filecontents1=classid[i] + "," +total_str[i] + "," +pass_str[i] + "," +yield_str[i]+ "/n";
             mFile.WriteString(filecontents1);
         }
          AfxMessageBox(" 数据成功写入classTotal1.txt",MB_OK);
          mFile.Close();
7.       待续……..
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值