加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:47:35 所属栏目:百科 来源:网络整理
导读:我正在尝试使用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::bin
我正在尝试使用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='';
ofstream f("s.txt");
while(!in.eof())
{
    in>>a;
    f<<a;
}

编辑:使用in.read(a,1);而不是>> a;解决了读取问题,但我需要写无符号字符和f.write(a,1);不接受未签名的字符.有没有人用无符号字符进行写作?

解决方法

#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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读