outputting files with a zero in them

Hello,

I've posted this question before, but no one answered me...

I want to output a bunch of data (contained in a buffer on a block of memory) in which there are zeros in the data. I try to output using the following code:

1
2
3
ofstream outputFile;
outputFile.open ("filename.txt");
outputFile << buffer;


whenever the buffer hits a zero, the writing to my hard drive terminates. I suspect that it has something to do with writing null terminated strings, in which my buffer is being treated like a string (when it hits a zero, it thinks its done and stops). How do I get around this problem?

The only workaround i have found for this is to have code like this:

1
2
3
4
5
6
ofstream outputFile;
outputFile.open ("filename.txt");
for (int i = 0; i < size ; i++)
{
     outputFile << buffer[i];
}


But this is terribly inefficient and since I'm writing multiple GB at a time...it takes way, way too long.

Please help!
Last edited on
If you do not mind using the C standard library, using stdio.h then you can use the fwrite function:
http://www.cplusplus.com/reference/clibrary/cstdio/fwrite/

In the fwrite function one of the parameters specified is the size of the buffer, so it writes the bytes from your buffer until it reaches the specified size, instead of until it hits a zero.

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

// ...

FILE* file = fopen("filename.txt", "wb");

fwrite(buffer, 1, sizeof(buffer), file);

// ...
in C++ you can write a code like
1
2
3
4
ofstream file( "filename.txt" , ios::binary );
...
...
file.write( reinterpret_cast< char *>( buffer ) , sizeof( buffer )); 
Dufresne,

Thanks for your response. I gave that method a try, well, at least without all that other stuff in there and it works. The only problem is that it seems to be very slow as compared to using the << operator. Currently my program is writing well over 16GB of data and using the .write() method seems to take twice the time as the << operator. Is there a faster, more efficient method to do this? I need the speed!

Also, can you please explain to me what this means:

reinterpret_cast< char *>( buffer )

I'm just a beginner and you've lost me...
Topic archived. No new replies allowed.