代码如下:
试着读了一个TXT文件,就能显示正确的字节数,另外要说明的是,我读入的位图,还是可以正确的画在对话框上。说明位图确实是载入了,但是不明白为什么CString.GetLength()不正常。
二进制数据最好用
CByteArray
而非cstring
来存放
CString::GetLength()的计算是遇到_T('\0')字符就结束了
因为2进制文件中包含'\0'字符,就是字符串末尾,当读到这个时就结束了,
42 4D 38 06 00 ... BMP...
这是BMP的开头,你应该明白为何只能读4个字符了吧,而楼上说的就是正解了
全部原因就在这里
你为什么要用CString存数据
CString是处理字符串的
处理字节流应该用BYTE数组
class CByteArray : public CObject
{
DECLARE_SERIAL(CByteArray)
public:
// Construction
CByteArray();
// Attributes
int GetSize() const;
int GetUpperBound() const;
void SetSize(int nNewSize, int nGrowBy = -1);
// Operations
// Clean up
void FreeExtra();
void RemoveAll();
// Accessing elements
BYTE GetAt(int nIndex) const;
void SetAt(int nIndex, BYTE newElement);
BYTE& ElementAt(int nIndex);
// Direct Access to the element data (may return NULL)
const BYTE* GetData() const;
BYTE* GetData();
// Potentially growing the array
void SetAtGrow(int nIndex, BYTE newElement);
int Add(BYTE newElement);
int Append(const CByteArray& src);
void Copy(const CByteArray& src);
// overloaded operator helpers
BYTE operator[](int nIndex) const;
BYTE& operator[](int nIndex);
// Operations that move elements around
void InsertAt(int nIndex, BYTE newElement, int nCount = 1);
void RemoveAt(int nIndex, int nCount = 1);
void InsertAt(int nStartIndex, CByteArray* pNewArray);
// Implementation
protected:
BYTE* m_pData; // the actual array of data
int m_nSize; // # of elements (upperBound - 1)
int m_nMaxSize; // max allocated
int m_nGrowBy; // grow amount
... ...
CByteArray
CByteArray类的成员
类CByteArray支持以字节为单位动态建立数组。
类CByteArray的成员函数与类CObArray的成员函数类似。因此,也可以参考类CObArray的文档。只需把函数参数或返回值中出现的CObject指针换成BYTE就可以了。例如,类CObArray中的函数:
CObject* CObArray::GetAt( int ) const;
在类CByteArray中对应的就是
BYTE* CByteArray::GetAt( int ) const;
CByteArray中包含了宏IMPLEMENT_SERIAL,以支持对象的串行化和转储。如果字节数组被存到了档案中,不管使用覆盖的操作符“<<”或成员函数Serialize,则其中的元素被串行化。
注意:
在使用数组之前,要调用SetSize设置它的大小并分配内存。如果没有使用SetSize,在数组中增加元素会引起数组内存空间频繁的重新分配以及数据拷贝。内存频繁的重新分配和数据拷贝会影响性能并造成内存碎片。
如果需要对数组中每个元素的输出调试信息,就要把CDumpContext对象的深度设置为1或更大。
构造函数
CByteArray构造一个空的字节数组
边界
GetSize取数组中元素的个数(数组大小)
GetUpperBound返回数组的最大有效下标
SetSize设置数组元素的个数(数组大小)
操作
FreeExtra释放数组中当前已有数据的最大上界后所有未占用的内存
RemoveAll删除数组中所有的元素
元素存取
GetAt返回指定下标处的数组元素的值
SetAt给数组中指定下标的元素赋值,但不能动态增长数组(指定的下标不能越界)
ElementAt返回对数组中某个字节的临时参考
GetData允许访问数组中的元素。可以为NULL
数组增长
SetAtGrow给数组中指定下标的元素赋值,在下标越界时动态增长数组Add在数组末尾增添一个元素,必要时增长数组Append在数组末尾接上另一个数组,必要时增长数组
Copy把另一个数组的内容拷贝到本数组,必要时增长数组
插入/删除
InsertAt在指定的下标处插入元素(或另外一个数组的内容)
RemoveAt删除指定下标处的一个元素
操作符operator[]取指定下标处元素的值,或者给其赋值
评论