我想写一个功能的测试仪,它需要从一个文件到另一个文件逐位写信息。我很确定我的BitOutputStream类能够工作,因为下面的代码按照预期打印出'A'。但是当我将代码更改为下面的第二个版本时,它将输入文件写入并写入输出文件,但输入与输出不匹配。我不确定是否无意中更改了我不应该的内容,或者输入文件具有导致发生不匹配或字节移位的某些“隐藏”字符。我怀疑我可能没有正确使用get()。任何帮助将不胜感激。如何将字节表单输入写入输出文件?
/*第一(工作)版本*/
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;
}
/*第二(非工作)版本*/
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;
}
第一个版本我与
./a.out
调用
我拨打的第二个版本
./a.out input output
它打印向终端指示writeBit被称为3次,但我预期它被称为8次“A”,所以为什么只有3次?
输入文件中只有'A'。 输入文件调用hexdump都产生:
0000000 0a41
0000002
呼吁hexdump都可以对输出文件生成:
0000000 0005
0000001
而且为什么hexdump都产生前7份0的0A-'linefeed '和41'A',什么最后是'0000002'的意思吗?我可以在代码的第二个版本中更改什么,以便输入和输出匹配的hexdump?
编辑:这里是BitOutputStream
#ifndef BITOUTPUTSTREAM_HPP
#define BITOUTPUTSTREAM_HPP
#include <iostream>
class BitOutputStream {
private:
char buf; // one byte buffer of bits
int nbits; // how many bits have been written to buf
std::ostream& out; // reference to the output stream to use
public:
/* Initialize a BitOutputStream that will
* use the given ostream for output.
* */
BitOutputStream(std::ostream& os) : out(os) {
buf = nbits = 0; // clear buffer and bit counter
}
/* Send the buffer to the output, and clear it */
void flush() {
out.put(buf);
buf = nbits = 0;
}
/* Write the least sig bit of arg into buffer */
int writeBit(int i) {
// If bit buffer is full, flush it.
if (nbits == 8)
flush();
int lb = i & 1; // extract the lowest bit
buf |= lb << nbits; // shift it nbits and put in in buf
// increment index
nbits++;
return nbits;
}
};
#endif // BITOUTPUTSTREAM_HPP
我明白一个位和一个字节之间的差异,我的第一句话应该说“一点一点”,而不是我编辑的“逐字节”。我的类BitOutputStream完全按照你所描述的 - 读取字节,将它们转换为位并写入每一位,这正是我想要的。但是在编写测试程序时,我的输入和输出文件不匹配,我想知道为什么。 – Napalidon
如果您逐字节复制,您也一点一点地复制,除非我遗漏了一些概念。 –
没有看到BitOutputStream的声明和定义,我不能给你任何更详细的帮助。 –