#include "ofile.h"
OFile::OFile()
{
mFIlePath = "";
mMode = NULL;
m_fp = NULL;
mType = UNKNOW;
isOpen = false;
}
void OFile::setFilePath(std::string path, FILE_OPENTYPE type)
{
mFIlePath = path;
mMode = getType(type);
mType = type;
}
bool OFile::open()
{
if((m_fp=fopen(mFIlePath.c_str(),mMode))==NULL)
{
printf("file cannot open \n");
//exit(0); 头文件#include <stdlib.h>
//exit结束程序,一般0为正常推出,其它数字为异常,其对应的错误可以自己指定。
return false;
}
isOpen = true;
return true;
}
bool OFile::write(char *str, int len)
{
if(m_fp == NULL)
{
return false;
}
int retLen = fwrite(str,1,len,m_fp);
if(retLen == len)
{
if(mType == ReadWrite)
{
rewind(m_fp);
}
return true;
}
else
{
return false;
}
}
int OFile::getFileSize()
{
if(m_fp == NULL)
{
return 0;
}
fseek(m_fp, 0L, SEEK_END);
return ftell(m_fp);
}
bool OFile::isExist()
{
if(!isOpen)//未打开
{
if((m_fp=fopen(mFIlePath.c_str(),"r"))==NULL)
{
return false;
}
else
{
fclose(m_fp);
return true;
}
}
else
{
return true;
}
}
bool OFile::deleteFile()
{
if( remove(mFIlePath.c_str()) == 0 )
return true;
else
return false;
}
bool OFile::clearFile()
{
if(m_fp != NULL)
{
fclose(m_fp);
fopen(mFIlePath.c_str(),"w");
fclose(m_fp);
fopen(mFIlePath.c_str(),mMode);
return true;
}
else
{
fopen(mFIlePath.c_str(),"w");
fclose(m_fp);
return true;
}
}
void OFile::close()
{
if(m_fp != NULL)
{
fclose(m_fp);
isOpen = false;
}
}
char *OFile::getType(FILE_OPENTYPE type)
{
if(type == ReadOnly)
{
return "rb";
}
else if(type == WriteOnly)
{
return "ab";
}
else if(type == ReadWrite)
{
return "ab+";
}
}
int OFile::read(char* str,int len)
{
if(m_fp == NULL)
{
return false;
}
int retLen = fread(str,1,len,m_fp);
return retLen;
}
头文件
#ifndef OFILE_H
#define OFILE_H
#include <string>
#include <stdio.h>
#include <iostream>
enum FILE_OPENTYPE
{
ReadOnly = 0,//仅读 rb
WriteOnly,//仅写 //ab 不存在会创建文件
ReadWrite,//读写 ab+ 不存在会创建文件
UNKNOW
};
class OFile
{
public:
OFile();
void setFilePath(std::string,FILE_OPENTYPE mode);
bool open();
bool write(char* str,int len);
int read(char*,int);
int getFileSize();
bool isExist();
bool deleteFile();
bool clearFile();
void close();
bool isOpen;
private:
FILE *m_fp;
std::string mFIlePath;
char * mMode;
FILE_OPENTYPE mType;
char * getType(FILE_OPENTYPE);
};
#endif // OFILE_H