How to write a byte form input to output files?
I am trying to write a tester for a function that takes writes info bit by
bit from one file to another. I am pretty sure that BitOutputStream class
works since the code below prints out an 'A' as expected. But when I
change the code to the second version below that takes the input file and
writes the output file the input does not match the output. I am not sure
if I am inadvertently changing something I shouldn't or the input file has
certain "hidden" characters that cause the mismatch or byte shifting to
occur. I suspect I might not be using get() correctly. Any help would be
greatly appreciated.
/* first (working) version */
int main(int argc, char* argv[])
{
BitOutputStream bos(std::cout); // channel output to stdout
bos.writeBit(1);
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(0);
bos.writeBit(1);
// prints an 'A' as expected
return 0;
}
/* second (non-working) version */
int main(int argc, char* argv[])
{
std::string ifileName = std::string(argv[1]);
std::string ofileName = std::string(argv[2]);
ofstream ofile;
ifstream ifile;
if(ifile)
ifile.open(ifileName, ios::binary);
if(ofile)
ofile.open(ofileName, ios::binary);
BitOutputStream bos(ofile);
int i;
while (ifile.good()) {
i = bos.writeBit(ifile.get()); // could the error be due to incorrect
usage of get()?
std::cout << i << std::endl; // just to see how many bits have been
processed
}
bos.flush();
ifile.close();
ofile.close();
return i;
}
The first version I call with
./a.out
The second version I call with
./a.out input output
which prints 1 2 3 to the terminal indication writeBit was called three
times but I expected it to be called 8 times for 'A', so why 3 times only?
input file has just 'A' in it. calling hexdump on input file generates:
0000000 0a41
0000002
calling hexdump on output file generates:
0000000 0005
0000001
Also why does hexdump generate 7 0's before 0a-'linefeed' and 41-'A' and
what is the meaning of '0000002' at the end? What can I change in the
second version of the code so the hexdump for input and output match?
No comments:
Post a Comment