views:

90

answers:

2

I've created a program in C++ that prompts the user for a filename and for the requested filesize. The program checks if the requested filesize is bigger than the actual filesize and then adds null characters (the ones with code 0) at the end of the file, until the requested filesize is reached.
I have done it like this (with fstream):

for (blah blah) {
    file << '\0'; // ('file' is an fstream object)
}

and it worked just as I wanted it to. I know this is a very, very bad code as it may torture the hard disk by sending many calls to it (and it's slow by the way). This was only for testing reasons. Then, because of this problem I decided to create a variable storing the NULL characters and save the whole variable to the file at once (without saving each character separately).
Then the problem appeared... because of the NULL character (also known as null-terminator), terminating the string, I couldn't store those zeros in any way.
I've tried an array of chars, a string and even a stringstream, but none worked (there's something interesting about stringstream, when I used it, the file's content looked like this: 0x47c274). Anyway, it didn't work as I expected it to.
Is there any efficient way of storing an array of null-characters?

+2  A: 

Store them in an array of characters and use ostream::write to write the array to the file.

Turtle
Thank you, it works the way with ofstream::write :) I've accepted Hugo Peixoto's answer, but your one is also good. ;)
rhino
+2  A: 

Here's an example:

#include <algorithm>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  ofstream fout("pokemon");
  char buffer[1000];
  std::fill(buffer, buffer + 1000, '\0');
  fout.write(buffer, sizeof(char) * 1000);
  return 0;
}
Hugo Peixoto
Thanks! I'm just curious, why did you include algorithm? `std::fill` isn't declared there, is it?
rhino
std::fill is declared in a common algorithms file, which is probably included by iostream and/or fstream already. If you just want to use fill, the header to include is algorithm, but in this case it wasn't needed.
Hugo Peixoto
or `char buffer[1000] = {};`
Potatoswatter
@Potatoswatter, what is the difference? It looks different, but I think it does the same, doesn't it?
rhino
@rhino: It's shorter and it doesn't require `<algorithm>`.
Potatoswatter