Please help Save binary data using FileWrite

Please help!
I'm trying to save binary data using FileWrite in Borland C++ Builder 6.
I'm reading the DATA from file like this:
1
2
3
4
5
6
   int iDATAHandle = FileOpen(filename, fmOpenRead);
   DATA = new int [Size];
   char *buf = new char[2*Size];
   FileRead(iDATAHandle, buf, 2*Size);
   for (int ii=0;ii<Size;ii++) 
       {DATA[ii] = Shortint(buf[2*ii])*256 + Byte(buf[2*ii+1]);}


then I do some operations with the DATA[i]
and then try to save it in the same manner:

1
2
3
4
5
6
7
8
9
10
   int iDATAHandle2 = FileCreate(filename2, fmOpenWrite);
  unsigned char *buf1 = new unsigned char[1];
  unsigned char *buf2 = new unsigned char[1];
  for (int i=0;i<Size;i++)
    {
     buf1 = (unsigned char *) (DATA[i]/256);
     buf2 = (unsigned char *) (DATA[i] - (DATA[i]/256) * 256);
     FileWrite(iDATAHandle2, &buf1, 1);
     FileWrite(iDATAHandle2, &buf2, 1);
    }

But the data is saved incorrectly. Looks like something else is saved, not my data.
What is wrong with it?

Thanks in advance!
Last edited on
Why are you using dynamic allocation for buf1 and buf2? Why two buffers anyway?
In line 5+6 you cast integers to pointers. That makes no sense.
In line 7+8 you write the first byte of each of said pointers, which also makes no sense.
You probably meant this:

1
2
3
4
5
6
7
unsigned char buf[2];
for (int i=0;i<Size;i++)
{  
  buf[0]=Bin[i]/256;
  buf[1]=Bin[i]&255;
  FileWrite(iDATAHandle2,buf,2);
}
Last edited on
I used two buffers because i need to swap bytes sometimes (producing files for Win and for unix).
But your method does the same and much easier!
Thanks again! It works!
Topic archived. No new replies allowed.