我正在学习C++,需要以二进制模式读取文件。下面是我按照C++参考文档所做的操作:
unsigned values[255];
unsigned total;
ifstream in ("test.txt", ifstream::binary);
while(in.good()){
unsigned val = in.get();
if(in.good()){
values[val]++;
total++;
cout << val <<endl;
}
}
in.close();
因此,我逐字节读取文件,直到in.good()
为真。我在while
循环的末尾放置了一些cout
,以便了解发生了什么情况,以下是输出:
marco@iceland:~/workspace/huffman$ ./main
97
97
97
97
10
98
98
10
99
99
99
99
10
100
100
10
101
101
10
221497852
marco@iceland:~/workspace/huffman$
现在,输入文件“test.txt”只是这样的:
aaaa
bb
cccc
dd
ee
一切都运行正常直到最后,出现了221497852这个问题。我猜测它可能与文件结尾有关,但是我无法找出问题所在。
我正在使用64位debian机器上的gedit和g++。
非常感谢您的帮助。
Marco