C++编程思想3-利用C++进行文件操作封装C函数

我们知道在C语言中许多文件操作的函数 很零散,在使用的时候不得不四处查找 ,我们是否能向C++中 的   CFile类等一样封装我们自己的文件操作呢?当然可以,我们这里我封装的是 C语言的文件操作函数  。实际上我们可以直接封装win32的API 函数 利用文件句柄进行文件操作,MFC的CFile类封装的就是 WIN32的API ,这里我只做测试用C来实现封装类File ,下面的File类可以实现对文件的读写 以及清空功能,简单的功能反应出面向对象的程序设计的好处,将对文件袋饿操作封装成了一个整体,文件有了自己的属性和行为。

对于FILE结构体指针 我们应该设计其为私有,这样做的是为了隐藏底层实现,从而实更好的封装,用户程序员只需要根据我们提供的接口进行文件操作 ,而不必考虑细节的实现。  我们对文件操作现在由分散转换成了集中,好处在自己编写代码的过程中就有所体会。。。

#ifndef  FILE_CLASS_DEFINE
#define  FILE_CLASS_DEFINE
#include <stdio.h>
#include "stdlib.h"
#include "string.h"
#include "windows.h"
class File
{
public:
 File()
 {
  this->f=NULL ;
  this->path="" ;
  this->modeAttribute="";
 }
 File(char*path,char * mode)
 {
  FILE *p =fopen(path,mode) ;
  this->path=path;
  this->modeAttribute=mode ;
  if(p==NULL)
  {  
   printf("文件打开失败!\n") ;
   return ;
  }
  this->f=p;
 }
 ~File()
 {  
  if (!this->f==NULL)
  {
   fclose(this->f) ;
  }
  
 }
 bool WriteTextToFile(char nChar[],int length)
 {  
  if(this->f==NULL)
  {
   printf("请先打开文件!\n")  ;
  }
  int item= fwrite(nChar,1,length,this->f) ;
  if (item<length)
  {
   return false ;
  }
  return true ;
 }
 FILE * GetFilePointer()
 {
  return this->f;
 }
 int  ReadAllText(char buf[])
 {    
  char tem[11] ="";
  while (!feof(f))
  {  
   memset(tem,0,11) ;
   int len=fread(tem,1,10,this->f);
   strcat(buf,tem);
  }
  
  return 1;
 }
 void CloseFile()
 {
  fclose(this->f) ;
 }
 void ClearFile()
 {  
  this->CloseFile() ;//关闭文件
  DeleteFile(this->path) ;
  this->f=fopen(this->path,this->modeAttribute) ;
 }
private:
 FILE * f ;  //隐藏实现细节
 char * path ;
 char * modeAttribute  ;
 
};
#endif

void main()
{
 File  f("d:\\1.txt","a") ;
 char buf[100]="this is a test!" ;
 f.WriteTextToFile(buf,strlen(buf)) ;
 f.CloseFile() ;
 File f2("d:\\1.txt","a+");
 f2.ReadAllText(buf) ;
 printf(buf) ;
 f2.ClearFile() ;
}

 

 

 

IO格式化控制操做算子

 #include <iostream>
using namespace std ;
void main()
{  
  //操作算子的应用 进行格式控制等等 这些操作算子都在 IOSTREAM.H头文件中定义
   cout<<hex<<"0x"<<443<<endl ;
   cout<<oct<<"0"<<443<<endl ;
   cout<<dec<<443<<endl ;
   cout<<flush ;//只刷新缓冲区 
   cout<<endl ;//刷新缓冲区并且换行   清空缓冲区中没有输出地数据
   cout<<ends ; //和endl一样仅仅用于 strstreams


}

posted on 2011-12-30 11:39  风尘女子  阅读(347)  评论(0编辑  收藏  举报

导航