开发者

Storing NUL characters (ASCII 0)

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 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 NUL characters and save the whole variable to the file at once (without saving each character separately).

Then the problem appeared... because of the NUL 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?


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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜