Dun*_*nci 3 c++ fstream bitmap
我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:使用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()
);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
几个问题:
while(!in.eof())
{
in>>a;
f<<a;
}
Run Code Online (Sandbox Code Playgroud)
不是读取文件的正确方法 - 您需要检查读取是否有效:
while( in >> a)
{
f<<a;
}
Run Code Online (Sandbox Code Playgroud)
其次,如果要以二进制模式读取文件,则需要使用read()和相关函数 - 无论文件在何种模式下打开,>>运算符始终执行格式化(非二进制)输入.
编辑:写需要一个演员:
unsigned char c = 42;
out.write( (char *) & c, 1 );
Run Code Online (Sandbox Code Playgroud)