读写文件的简单封装

读写文件的简单封装

class FileClassWrap
{
private:
    std::string file_path_;
    FILE* fp_;
public:
    FileClassWrap(const std::string &filePath,const char* mode) : file_path_(filePath),fp_(nullptr) {
        fp_ = fopen(file_path_.c_str(), mode);
    }
    virtual ~FileClassWrap() {
        if(fp_!= nullptr)
        {
            fclose(fp_);
        }
    }

    bool open()
    {
        return fp_!= nullptr;
    }

    bool fswrite(uint8_t* ptr, uint32_t size, uint32_t addr= 0)
    {
        if(fp_== nullptr)
        {
            return false;
        }
        int feek_ret=fseek( fp_, addr, SEEK_SET );
        if(feek_ret!=0)
        {
            return false;
        }
        int  wsize=::fwrite(ptr,size,1,fp_);
        if(wsize!=1)
        {
            return false;
        }
        return true;
    }

    uint32_t fsread(uint8_t* buf, uint32_t block_size, uint32_t block_cnt, uint32_t addr= 0)
    {
        if(fp_== nullptr)
        {
            return 0;
        }
        int feek_ret=fseek( fp_, addr, SEEK_SET );
        if(feek_ret!=0)
        {
            return 0;
        }
        int len=::fread(buf, block_size,block_cnt, fp_);
        return len;
    }
    uint32_t fsreadAll(uint8_t* buf, uint32_t buff_size)
    {
        if(fp_== nullptr)
        {
            return false;
        }
        int feek_ret=fseek( fp_, 0, SEEK_SET );
        if(feek_ret!=0)
        {
            return false;
        }
        int len=::fread(buf, 1,buff_size, fp_);
        return len;
    }
};
posted @ 2022-06-02 10:01  zongzi10010  阅读(61)  评论(0编辑  收藏  举报