Link to home
Start Free TrialLog in
Avatar of aslamshikoh1
aslamshikoh1

asked on

Write a Byte array to a file

How can i write a byte array,for eg:

BYTE *buf = new BYTE[200];
buf=somedata ;

into a file,for eg "bytedata.dat"

please provide some good eg
Avatar of jkr
jkr
Flag of Germany image

The easiest way would be to

#include <stdio.h>

//...


BYTE *buf = new BYTE[200];

//...

FILE* p = fopen(bytedata.dat","wb");

fwrite(buf, 1, 200);

fclose(p);
Or, more on the C++ side:

#include <fstream>
using namespace std;


BYTE *buf = new BYTE[200];

//..


ofstream os("bytedata.dat", ios_base::out | ios_base::binary);

os.write(buf,200);

os.close();
Don't forget to free your buffer
BYTE *buf = new BYTE[200];
delete [] buf;

Open in new window

Also, in C++ consider using std::string instead...
http://msdn2.microsoft.com/en-us/library/syxtdd4f(VS.80).aspx
An example using strings and streams...
#include <string>
#include <iostream>
#include <fstream>
 
int main()
{
	// The data we wish to write to file
	std::string sData("Hello world");
 
	// Open the file as a stream (destructor will close for us)
	std::ofstream ofs("c:\\temp\\data.txt");
 
	// If file was opened ok...
	if(ofs.is_open())
	{
		// Write out data to it
		ofs << sData;
 
		// If write error then report it
		if(!ofs.good())
		{
			std::cerr << "Failed to write data" << std::endl;
		}
	}
 
	return 0;
}

Open in new window

Avatar of aslamshikoh1
aslamshikoh1

ASKER

Ok i got it but i have a continuous stream of bytes to write to a file.Its a thread which has a while loop like this:

while(oEditStreamImpl->isActive_  && --count)
      {
            

            ofstream os("bytedata.dat", ios_base::out | ios_base::binary);
                 os.write(buf,200);
}

os.close()

so how can i append the data to end of the file,like something to do with the file pointer,right now data is getting overwritten.
also write(buf,200) complains about not able to accept a byte,i guess a char array is what it accepts,so im just casting it like

write((char*)buf,200)

is it OK to do this
ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

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
SOLUTION
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
>> is it OK to do this
Yes, a stream expects a char * but you can cast any pointer type to that as long as you specify correctly the number of chars when writing it out. It helps if you just think of it as writing signed bytes.

NB. a wide stream expects wchar_t *
btw, this :

        BYTE *buf = new BYTE[200];
        buf=somedata ;

creates a memory leak ... you're overwriting the pointer to the allocated 200 bytes with a new value.