windowsnullbatch-fileascii

How can I write a null ASCII character (nul) to a file with a Windows batch script?


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.


Solution

  • 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