我正在尝试使用 fstream 读取 bmp 文件。 但是它会跳过 08 和 0E(十六进制)之间的值 例如,对于值 42 4d 8a 16 0b 00 00 00 00 00 36
上面写着
42 4d 8a 16 00 00 00 00 00 36
跳过 0b,就像它甚至不存在于文档中一样。
怎么办?
代码:
ifstream in;
in.open("ben.bmp", ios::binary);
unsigned char a='\0';
ofstream f("s.txt");
while(!in.eof())
{
in>>a;
f<<a;
}
编辑:使用 in.read(a,1);
而不是 in>>a;
解决了读取问题,但我需要编写无符号字符和 f.write(a,1);
不接受无符号字符。有人有用无符号字符进行写作的功能吗?
最佳答案
如果你想一次一个字节地读取文件,这是 istream 缓冲区迭代器的一个很好的用途。
int main()
{
ifstream in("ben.bmp", ios::binary);
ofstream f("s.txt");
//
// Note: this is NOT istream_iterator
// The major different is that the istreambuf_iterator does not skip white space.
//
std::istreambuf_iterator<char> loop(in);
std::istreambuf_iterator<char> end;
for(; loop != end; ++loop)
{
f << (*loop);
}
// You could now also use it with any of the std algorithms
// Alternative to Copy input to output
std::copy(loop,end,std::ostream_iterator<char>(f));
// Alternative if you want to do some processing on each element
// The HighGain_FrequencyIvertModulator is a functor that will manipulate each char.
std::transform( loop,
end,
std::ostream_iterator<char>(f),
HighGain_FrequencyIvertModulator()
);
}
关于c++ - fstream 跳过字符而不读取位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2031007/