文本文件和二进制文件之间的准换

本程序要自己创建个文本格式的输入文件a1.txt,编译后能将文本文件前255字节以内的字符转换成相应的AscII码值的二进制表示,并存入输出文件a2.txt中。然后再将二进制文件还原并存入a3.txt文件。

具体代码如下:

#include <cstdio>
#include <stdio.h>
#include <string.h>
#define NSIZE  8

void print_2(int val2);
/***********文本文件转二进制**********/
void Text2Bin(const char* sIn,const char* sOut){
    char a[255];
    int count = 0;
    int ch;
    for(int j=0; j<255;j++)a[j]='\0';
    FILE* fin=fopen(sIn,"r");
    FILE* fout=fopen(sOut,"w");
    for(int i=0 ; i<=255 ; i++)fscanf(fin,"%c",&a[i]);
    for(int k=0 ; k<=254&&a[k] !='\0'; k++)
    {   
        ch = a[k];
        for(int a=7;a>=0;a--) fprintf(fout,"%d",ch>>a&1);
        //fprintf(fout,"\n");
    }
    fclose(fin);
    fclose(fout);
}
/***********二进制文件转文本文件**********/
void Bin2Text(const char* sIn,const char* sOut){
    FILE* fin=fopen(sIn,"r");
    FILE* fout=fopen(sOut,"w");
    char str[255*8];
    for(int r=0; r<255 ;r++) str[r]='\0';
    int i = 0, j = 0, iTemp = 0, flag = 0;
    int  ibina[NSIZE];          
    char cRead[NSIZE];              
    char cChar;
    for(int a=0 ; a<=255 ; a++)fscanf(fin,"%c",&str[a]);
    //for(int f=0 ; f<=255 ; f++)printf("%c",str[f]);
    while(flag <= 255){
        //printf("%d",flag);
        for(int b=flag ; b>=flag && b<flag+NSIZE ; b++)
        {
            //printf("%d",b%8);
            cRead[b%8] = str[b];
            //printf("%c",cRead[b%8]);
        }
        for(i = 0; i < NSIZE; i++)
        {
            ibina[i] = (cRead[i]-'0'); 
        }
        iTemp = 1;
        cChar = 0;
        for(j = 7; j >=0 ; j--)
        {
            //printf("%c",ibina[j]);
            //printf("%d\n",cChar);
            cChar+=ibina[j]*iTemp;
            iTemp *= 2;
        }
        printf("%c",cChar);
        fprintf(fout,"%c",cChar);
        flag=flag+8;
    }
    fclose(fin);
    fclose(fout);
}

int main(){
    Text2Bin("d:\\a1.txt","d:\\a2.txt");
    Bin2Text("d:\\a2.txt","d:\\b2.txt");
    printf("\nSuccessfully converted file!\n"); 
    return 0;
}
  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值