牛骨文教育服务平台(让学习变的简单)
博文笔记

C语言读写二进制流

创建时间:2015-10-26 投稿人: 浏览次数:2360

学习赫夫曼编码,对于如何把二进制流存入二进制文件或如何从二进制文件读出二进制流进行了研究, 总结网上诸多大侠的片言只语, 实现了这一功能。声明:本人只是在学习C语言,不能跟专业人士相提并论。
原理是用一组掩码与要读出或写入的字符进行位运算,逐个写入或输出二进制码流。

源码:

#include <stdio.h>
#define FILE_PATH "d:\1.dat"
char *bin="001101110110001000010000111100";
unsigned char mask[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; 
FILE *fp;

int BinRead(){
    unsigned char get[255];
    int  pos,p = 0;
    unsigned char ch;
    fopen_s(&fp,FILE_PATH, "rb"); 
    ch = fgetc(fp);
    while(!feof(fp)){
        for(pos=7;pos>=0;pos--){
            if(ch & mask[pos]) get[p]="1";
            else get[p]="0";
            p++;
        }
        ch = fgetc(fp);
    }
    get[p]="";
    printf("
%s
",get);
    fclose(fp);
    return  0;
}
int BinWrite(){
    fopen_s(&fp,FILE_PATH, "wb"); 
    int  pos = 7;
    unsigned char ch,put = 0x00;
    while((ch=bin[0])!=""){
        if (ch=="1")    put =  put  | mask[pos];
        bin ++;
        pos --;
        if(pos==-1) {
            fputc(put,fp);
            pos = 7;
            put = 0x00;
        }
    }
    if (pos<7) fputc(put,fp);
    fclose(fp);
    return  0;
}

int main(){
    BinWrite();
    BinRead();
    getchar();
    return 0;
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。