转换

来源:互联网 发布:房间平面图软件 编辑:程序博客网 时间:2024/04/29 23:06
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#define NSIZE  8                            // 每次读取字符数目为8


int main()
{


 FILE *txt_file,*bin_file;
 int mode = 0;
 int i = 0, j = 0, iTemp = 0;
 int nread;
 int binary[NSIZE];       // 存放二进制字节流


 char cRead;                     // 存储读文件流的数据
 char cWrite;
 char charater[NSIZE]; 
 char txt_fileName[50],bin_fileName[50]; 




 printf("Usage:Txt To Bin(0),Bin To Txt(1)\n");
 fscanf(stdin,"%d",&mode);


  if(mode)
  {


   txt_file = fopen("TxtData.txt","rb");
   bin_file = fopen("BinData.txt","wb"); 


   if (txt_file < 0) 
   {
    printf("can not open the input file!\n");
    return 0;
   }


   if(bin_file < 0)
   {
     printf("can not open the input file!\n");
     return 0;
   }


  while((fread(&cRead,1,1,txt_file) > 0))
  {
 for(i = 1; i <= NSIZE; i++) 
 {
  if((1 << NSIZE - i) & cRead)
  {
   binary[i] = 1;
  }   
  else
  {
   binary[i] = 0;
  }
   printf("%d",binary[i]);
   fwrite(&binary[i],1,1,bin_file);
    }  
  }
  printf("\n");


  fclose(txt_file); 
  fclose(bin_file);
  }
  else
{
  
   bin_file = fopen("BinData.txt","rb"); 
   txt_file = fopen("TempData.txt","w");


  if (bin_file < 0) 
  {
   printf("can not open the input file!\n");
   return 0;
  }


  if(txt_file < 0)
  {
   printf("can not open the input file!\n");
   return 0;
  }


  while((fread(charater,NSIZE,1,bin_file) > 0))
 { 
 // 将字符转换为0101形式后存入整型数组
 for(i = 0; i < NSIZE; i++)
 {
  binary[i] = (charater[i] - '0');    // 减'0'才能保存为0101形式,否则会保存为ASCII码形式
 }


 // 每8位为一个字节进行还原
 iTemp = 1;
 cWrite = 0;
 for(j = 7; j >= 0; j--)
 {
  cWrite += binary[j] * iTemp;
  iTemp *= 2;
 }
 printf("%c",cWrite);
 fwrite(&cWrite,1,1,txt_file);
}
 printf("\n");
 fclose(txt_file); 
 fclose(bin_file); 
}
 
  return 0;
}
0 0
原创粉丝点击