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


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值