title: Reading/writing a bmp file
body: <p>I wrote a code to simply read/write (copy) a *.bmp file. But something is wrong my program runs over and over and over again ... I mean it looks like there is a while(true) loop inside or something. Heres my code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #pragma pack(push, 1)
  typedef struct Pix
  {
    unsigned char R;
    unsigned char G;
    unsigned char B;
    unsigned char L;
    int BW;
  }Pix;
  #pragma pack(pop)
  
  #pragma pack(push, 1)
  typedef struct BitMap
  {
      short Signature;
      long Reserved1;
      long Reserved2;
      long DataOffSet;
  
      long Size;
      long Width;
      long Height;
      short Planes;
      short BitsPerPixel;
      long Compression;
      long SizeImage;
      long XPixelsPreMeter;
      long YPixelsPreMeter;
      long ColorsUsed;
      long ColorsImportant;
      struct Pix *pixels
  }BitMap;
  #pragma pack(pop)
  
  int main(int argc, char **argv)
  {
  
  unsigned long int i=0;//to count pixels readed
  unsigned long int S=0;//number of pixcels to read
  
  struct BitMap source_info;//to store bitmap info header
  struct Pix source_pix;// to store pixcels
  
  FILE *fp;//file pointer for source file
  FILE *Dfp;//file ponter for distenation file
  
  if(!(fp=fopen("in.bmp","rb")))//open in binery read mode
  {
  printf(" can not open file");//prind and exit if file open error
  exit(-1);
  }
  
  
  Dfp=fopen("out.bmp","wb");//opne in binery write mode
  //read the headers to souirce file
  fread(&amp;source_info, (sizeof(long)*3 + sizeof(short)),1,fp);
  
  //calucate the number of pix to read
  S=source_info.Width*source_info.Height;
  source_info.pixels =  (struct Pix *) malloc(sizeof(struct Pix)*S);
  
  //read pixcels
  for(i=1;i&lt;=S;i++)
  {
  //read pixcel form source file
  fread(&amp;source_pix,sizeof(struct Pix),1,fp);
  source_info.pixels[i-1] = source_pix;
  }
  
  // write header to dest file
  fwrite(&amp;source_info,  (sizeof(long)*3 + sizeof(short)),1,Dfp);
  // write pixels to dest file
  for(i=1;i&lt;=S;i++)
  {
      fwrite(&amp;source_info.pixels[i-1],sizeof(struct Pix),1,Dfp);
  }
  
  //close all fiels
  fclose(fp);
  fclose(Dfp);
  return 0;
  }
  </code></pre>