Link to home
Start Free TrialLog in
Avatar of dhirajbhise
dhirajbhise

asked on

Writing Byte Pointer to File

Hi,

I want to write
byte *a;
to a file. how can i write ?
 
ASKER CERTIFIED SOLUTION
Avatar of jemax
jemax

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ackava
ackava

/*
    The following code is to write byte * b into file
    NOTE : nSize is size of bytes pointed by *b
*/

int nSize = ...;

FILE * fp = fopen("yourfilename.ext","wb");
if(fp==NULL)
{
    // OOPS SOME ERROR
}
else
{
    fwrite(&nSize,4,1,fp);
    fwrite(b,nSize,1,fp);
    fclose(fp);
}


/*
    The following code is to read same thing from file
*/
int nSize = ...;

FILE * fp = fopen("yourfilename.ext","wb");
if(fp==NULL)
{
    // OOPS SOME ERROR
}
else
{
    fread(&nSize,4,1,fp);
    b = new byte [nSize];
    fread(b,nSize,1,fp);
    fclose(fp);

    // now you can use byte * b
}
Sorry a minor bug in my previous post, use this.

/*
   The following code is to write byte * b into file
   NOTE : nSize is size of bytes pointed by *b
*/

int nSize = ...;

FILE * fp = fopen("yourfilename.ext","wb");
if(fp==NULL)
{
   // OOPS SOME ERROR
}
else
{
   fwrite(&nSize,4,1,fp);
   fwrite(b,nSize,1,fp);
   fclose(fp);
}


/*
   The following code is to read same thing from file
*/
int nSize = ...;

FILE * fp = fopen("yourfilename.ext","rb");
if(fp==NULL)
{
   // OOPS SOME ERROR
}
else
{
   fread(&nSize,4,1,fp);
   b = new byte [nSize];
   fread(b,nSize,1,fp);
   fclose(fp);

   // now you can use byte * b
}
A short note: Why are you writing a POINTER to a file? Unless you are using this for diagnostics it carries very little information. The next time you run your application, this pointer is completely worthless since it most definately changed. If you are using MSVC and run your application in debug mode it will be the same to make debugging easier; in release build, however, it will point to a different location in memory.
fl0yd,

Is the feature of the MSVC debug mode documented, or it's only and observation? (I observed this myself.)

Thanks,
Kender
I read it somewhere -- don't remember where, though. I think it was some official ms paper, but don't hold me responsible for it ;)