以二进制方式读写jpg文件

时间:2022-04-10 18:51:43
long _filesize(FILE *stream) 
{ 
    long curpos, length; 
    curpos = ftell(stream); 
    fseek(stream, 0L, SEEK_END); 
    length = ftell(stream); 
    fseek(stream, curpos, SEEK_SET); 
    return length; 
} 

char* readBinFile(char* name,int& nSize)
{
    FILE *fp;
    if ((fp=fopen(name, "rb")) == NULL)
        return NULL;
    long buffsize = _filesize(fp);
    nSize = buffsize;
    char *buff = (char *)malloc(buffsize*sizeof(char));
    //printf("1--%d\n",buffsize);
    fread(buff, buffsize, 1, fp);
    fclose(fp);
    return buff;
}
int writeBinFile(char* name,char* buf, long nSize)
{
    FILE *fp = fopen(name,"wb");
    if (fp == NULL)
    {
        printf("无效文件句柄\n");
        return -1;
    }
    fwrite(buf,nSize,1,fp);
    //printf("2--%d\n",nSize);
    fclose(fp);
    return 0;
}

使用例子

int nSize = 0;//保存jpg二进制数据的大小
char* buf = readBinFile("111.jpg",nSize);
if (buf == NULL)
{
    printf("打开文件失败\n");
}
writeBinFile("112.jpg",buf,nSize);//简单测试,未对返回值做校验
//释放申请的内存
if (buf)
{
    free(buf);
    buf = NULL;
}