文本文件转二进制文件的实现

 /*
说明:

[text.txt]内容如下:
----------------------------------------------------------------------
I enjoyed coding this tool, I hope you are enjoying this by using it.

LivePhysics.Com
 
Developer Teamm
----------------------------------------------------------------------

转换出来的[bina.txt]内容如下:
----------------------------------------------------------------------
010010010010000001100101011011100110101001101111011110010110010101100100001000000110001101101111011001000110100101101110011001110010000001110100011010000110100101110011001000000111010001101111011011110110110000101100001000000100100100100000011010000110111101110000011001010010000001111001011011110111010100100000011000010111001001100101001000000110010101101110011010100110111101111001011010010110111001100111001000000111010001101000011010010111001100100000011000100111100100100000011101010111001101101001011011100110011100100000011010010111010000101110000011010000101001001100011010010111011001100101010100000110100001111001011100110110100101100011011100110010111001000011011011110110110100001101000010100100010001100101011101100110010101101100011011110111000001100101011100100010000001010100011001010110000101101101
----------------------------------------------------------------------

*/

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string>

using namespace std;
#define NSIZE  8                            // 每次读取字符数目为8

void main()
{
 ifstream ifile;
 ofstream ofile; 

 int i = 0, j = 0, iTemp = 0;

 int ibina[NSIZE];       // 存放二进制字节流
 char cRead;                     // 存储读文件流的数据

 ifile.open("text.txt", ios::in | ios::binary);
 ofile.open("bina.txt");

 if (!ifile)
 {
  cout << "cannot open file/n";
  return;
 }

    while(!ifile.eof())
    {
  ifile.read(&cRead, 1);

  for(i = 1; i <= NSIZE; i++)
  {
   if((1 << NSIZE - i) & cRead)
   {
    ibina[i] = 1;
   }  
   else
   {
    ibina[i] = 0;
   }

   ofile << ibina[i];
  } 
    }

 ifile.close();
 ofile.close();
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值