CFile file("D:\\Windows XP 关机.rar",CFile::modeRead|CFile::typeBinary);
char* pBuf = new char[file.GetLength()];
int len = file.GetLength();
file.Read(pBuf,file.GetLength());
file.Close();
struct FILE_INFO
{
char* spBuf;
};//定义一个结构体
FILE_INFO finfo;
CFile nfile("C:\\Windows XP 关机.rar",CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
finfo.spBuf = new char[len];//为结构体的一个成员初始化
strcpy(finfo.spBuf,pBuf);//将原先读取的pBuf赋值给结构体的成员spBuf;
if(strcmp(finfo.spBuf,pBuf) == 0)//比较两个是否相同(我得出的结果是相同)
{
MessageBox("xiang deng");
}
nfile.Write(finfo.spBuf,len);//将数据写入文件中
nfile.Close();
return;要读取一个压缩文件,先将该文件的数据读给pBuf,然后把pBuf赋值给finfo.spBuf,最后将finfo.spBuf写入文件当中,得出的结果是文件损坏了!!!!!!!!!!!!!!!!!!!!如果倒数第三行改为nfile.Write(pBuf,len),则得到的文件是正常的!!!这是什么原因呢?难道因为pBuf里面读的是二进制的数据就不能这么赋值吗?应该怎么办呢?

解决方案 »

  1.   

    strcpy(finfo.spBuf,pBuf);//将原先读取的pBuf赋值给结构体的成员spBuf;
    这句的问题 strcpy是字符串拷贝,pBuf里存的显然不是字符串,改成
    memcpy(finfo.spBuf,pBuf,len)
      

  2.   

    finfo.spBuf = new char[len];//为结构体的一个成员初始化
    memset(finfo.spBuf,0,len);初始化一下
      

  3.   

    //建议:
    //1、对于2进制文件,加上CFile::ModeBinary
    //2、对于2进制内容比较,用memcmp()
    //以上建议都是为了防止2进制文件中的0x00对读取和比较等操作产生影响