views:

502

answers:

3

I'm attempting to write an ASCII null character (nul) to a file from a Windows batch script without success. I initially tried using echo like this:

echo <Alt+2+5+6>

which seems like it should work (typing <Alt+2+5+6> in the command window does write a null character - or ^@ as it appears), but echo then outputs:

More?

and hangs until I press <Return>. As an alternative I tried using:

copy con tmp.txt >nul
<Alt+2+5+6><Ctrl+Z>

which does exactly what I need, but only if I type it manually in the command window. If I run it from a batch file it hangs until I press <Ctrl+Z> but even then the output file is created but remains empty.

I really want the batch file to stand alone without requiring (for example) a separate file containing a null character which can be copied when needed.

+2  A: 

Okay, this was tricky, and the solution is ugly, but it works.

You can use the batch file itself as the file containing the null character to be copied.

This batch file, called null.bat:

findstr /v /r \n null.bat >> myfile.txt
[NULL]

(where the last line contains only the null character) appends the null character to myfile.txt.

findstr /v /r shows all lines that aren't matched by the regex, i.e. only the last one, because there's no newline character.

I have tried several other things, but this was the only one I could find that didn't strip the null character.

Note: findstr was first shipped with Windows 2000 so may not be available on prior versions of Windows

balpha
That's exactly what I need, thanks!
Matthew Murdoch
+2  A: 

An alternative to the accepted answer which doesn't involve having to put null characters into the batch file is as follows:

@echo off

set NULL_FILE=null.txt
set DEBUG_COMMANDS=write-null.dbg

echo e 100 >%DEBUG_COMMANDS%
echo 0 >>%DEBUG_COMMANDS%
echo n %NULL_FILE% >>%DEBUG_COMMANDS%
echo rbx >>%DEBUG_COMMANDS%
echo 0 >>%DEBUG_COMMANDS%
echo rcx >>%DEBUG_COMMANDS%
echo 1 >>%DEBUG_COMMANDS%
echo w >>%DEBUG_COMMANDS%
echo q >>%DEBUG_COMMANDS%

debug < %DEBUG_COMMANDS% >nul

del %DEBUG_COMMANDS%

This is obviously more verbose and also has the downside that it won't work on Win64 machines (due to debug no longer being available in those environments).

Matthew Murdoch
+1  A: 

Here's an article which describes how to write arbitrary bytes with a batch file (search for h2b.com). This effectively solves the problem of writing any non-printable data using a batch script (including null).

Matthew Murdoch