我想寫一個功能的測試儀,它需要從一個文件到另一個文件逐位寫信息。我很確定我的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的聲明和定義,我不能給你任何更詳細的幫助。 –