fwrite output file, add other characters

Category: C/C++ -> C++ Author: az5313088 Date: 2001-12-14 14:51:52
 
az5313088
2001-12-14 14:51:52
As stated,
I use fwrite to save a bmp file, the content part of the image, compared with WinHex found some more character than the original.
derived code

int bmpfile::export_to(const char* file)
{
    FILE *fp = fopen(file, "w");
    if(!fp)
    {
        return 0;
    }

    //write the file header

    fwrite(&_fh, 1, sizeof(_fh), fp);
    //write the dib header
    fwrite(&_dib, 1, sizeof(_dib), fp);
    //it's a 255 color bmp
    if(_dib._depth == 8)
    {
        fwrite(_palette, 4, 256, fp);
    }

    fseek(fp, _fh._bmp_offset, SEEK_SET);
    
    int pitch = (_dib._depth>>3)*_dib._width;
    byte_t* tail  = _buffer+_dib._imagesz-pitch;
    for(int i=0; i<_dib._height; ++i)
    {
        fwrite(tail, 1, pitch, fp);
        tail -= pitch;
    }
    
    fclose(fp);

    return 1;    
}

personally think it is fwrite () problem, hope that the Supreme answer
loveboyzjj
2001-12-14 15:03:20
binary write Try
babaly2010
2001-12-14 15:17:02
binary write "wb"
b represents a binary
yeyeshishuaishuai
2001-12-14 15:31:53

try

#include <stdio.h>

int main ()
{
  FILE * pFile;
  char buffer[] = { 'x' , 'y' , 'z' };
  pFile = fopen ( "myfile.bin" , "wb" );
  fwrite (buffer , 1 , sizeof(buffer) , pFile );
  fclose (pFile);
  return 0;
}
lee1981576
2001-12-14 15:36:15
still the same result, fwrite refresh the content to the file, go there for buffer alignment problems? Many characters 0x0d (CR)
caowei2313
2001-12-14 15:46:27
in front of more than newline out of it
sunchao1213
2001-12-14 15:57:19
Solve the problem, is added in front newline cr, the binary write, front test was wrong.
tkx ~
zs610423
2001-12-14 16:07:22
this does not matter.