在C中创建位图-如何将/r/n写入1个字节? [英] Creating bitmap in C - How to write /r /n as 1 byte?

查看:55
本文介绍了在C中创建位图-如何将/r/n写入1个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在C中创建位图.首先,我要执行的操作是复制标头和其他位图文件中的所有像素数据.问题是数字"10",当我读时它只是1个字节,但是当我写时是2个字节.我知道/r/n的内容,但是例如Paint如何将其保存为1个字符?

I'm trying to create bitmap in C. Firstly what i want to do is copy header and all pixels data from other bitmap file. The problem is with number '10', which when i'm reading it's just 1 byte, but when i write it's 2 bytes. I know about /r /n things, but how for example Paint can save it as 1 char?

我正在以这种方式读取标题:

I'm reading header in this way:

unsigned char* header = malloc(54);
fread(header, sizeof(unsigned char), 54, file);

并以此方式书写:

fwrite(img->fileHeader, sizeof(unsigned char), 54, file);

推荐答案

在处理非文本文件时,必须始终使用ios::binary标志:

You have to use ios::binary flag when dealing with non-text files, always:

ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);

如果您使用的是Windows,并且在此处打开流时未指定ios::binary标志,会发生什么情况:

If you're using Windows and not specifying the ios::binary flag when opening your streams here what happens:

13 10序列将转换为10:内存中的数据已损坏.如果数据首先是二进制的,那么您将很不幸无法获得这些序列,但它可能会发生

13 10 sequences are converted to 10 when reading: corrupt data in memory. If the data is binary in the first place you'd be unlucky to get those sequences but it can happen

10会转换为13 10(CR + LF).这更有可能发生,并且会损坏您的输出文件.

10 is converted to 13 10 (CR+LF) when writing. That is more likely to happen and corrupts your output file.

注意:即使已损坏,也可以以文本形式读取和以二进制形式写回来修复损坏(或将13 10替换为10)

Note: even if it's corrupt, reading as text and writing back as binary fixes the corruption (or replace 13 10 by 10)

这篇关于在C中创建位图-如何将/r/n写入1个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆