繁体   English   中英

fstream在没有读取位图的情况下跳过字符

[英]fstream skipping characters without reading in 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;
}

编辑:使用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()
                          );
}  

几个问题:

while(!in.eof())
{
    in>>a;
    f<<a;
}

不是读取文件的正确方法 - 您需要检查读取是否有效:

while( in >> a)
{
    f<<a;
}

其次,如果要以二进制模式读取文件,则需要使用read()和相关函数 - 无论文件在何种模式下打开,>>运算符始终执行格式化(非二进制)输入。

编辑:写需要一个演员:

unsigned char c = 42;
out.write( (char *) & c, 1 );

operator>>operator<<设计用于文本输入和输出。

对于二进制文件,使用read()write()

这是因为流将字节解释为ascii字符。 08到0e是白色空格(水平制表符,换行符,垂直制表符,回车符等),它们被跳过。 像其他答案所说,你需要使用流的read()方法。

#include <fstream>
#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
  const char *bitmap;
  const char *output = "s.txt";

  if (argc < 2)
    bitmap = "ben.bmp";
  else
    bitmap = argv[1];

  std::ifstream  in(bitmap, std::ios::in  | std::ios::binary);
  std::ofstream out(output, std::ios::out | std::ios::binary);
  char a;

  while (in.read(&a, 1) && out.write(&a, 1))
    ;

  if (!in.eof() && in.fail())
    std::cerr << "Error reading from " << bitmap << std::endl;

  if (!out)
    std::cerr << "Error writing to "   << output << std::endl;

  return 0;
}

处理二进制数据时,使用read()而不是重载的按位运算符(<<和>>)

如果您需要使用流,可以执行以下操作:

std::ifstream ifs("bar", std::ios::in | std::ios::binary);
std::ofstream ofs("foo", std::ios::out | std::ios::binary);
ofs << ifs.rdbuf();

确保将其打开为二进制文件,如下所示:

ifstream ifs('input.bin', ios::in | ios::binary);

ofstream ofs('output.bin', ios::out | ios::binary);

检查ifs.good()以确保打开的文件一切正常也是一个好习惯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM