binary file parsing in C++

Justin Findlay findlay@cosmic.utah.edu
Wed Dec 10 23:20:00 GMT 2003


On Wed, 10 Dec 2003, Eljay Love-Jensen wrote:

>> Is there any way to read through a file bit by bit, instead of character by character?
> 
> You'll have to write your own bit-by-bit reader.
> 
> A class that HAS-A ifstream, and whose "get" method returns a bit (via bool or int or enum Bit { Zero, One }).
> 
> Shouldn't be very hard.


I am perplexed at what is happening here.  This is a simple script that 
reads a file one byte at a time, and writes it to another file one byte at 
a time, but somehow there is an extra character at the end of the output 
file.

$ g++ --version
g++ (GCC) 3.3.2 20031022 (Red Hat Linux 3.3.2-1)
$ g++ binary.cpp
$ ./a.out
$ ls -ls
 8 -rw-rw-r--    1 justin   justin       4258 Dec  9 20:11 bin
 8 -rw-rw-r--    1 justin   justin       4259 Dec 10 16:14 bout
$ cat binary.cpp
//binary.cpp
#include <fstream>

  using namespace std;

int main()
{
  char b[ 1 ];
  ifstream fin( "bin" );
  ofstream fout( "bout" );
  while ( fin.good() && ! fin.eof() )
  {
    fin.read( b, 1 );
    fout.write( b, 1 );
  }
  return 0;
}


Justin



More information about the Gcc-help mailing list