Zeroing a file from command-line
Solution 1:
Is there a built-in command in Windows to fill a file with zero / NULL bytes?
Yes. You can use fsutil
for this:
> fsutil file setzerodata /?
Usage : fsutil file setzerodata offset=<val> length=<val> <filename>
offset : File offset, the start of the range to set to zeroes
length : Byte length of the zeroed range
Eg : fsutil file setzerodata offset=100 length=150 C:\Temp\sample.txt
To zero fill a complete file you will need to use an offset of 0
and you will need to know the file length.
Can we use batch file that would compute the size automatically?
Of course.
Use the following batch file (zero.cmd):
@echo off
setlocal enabledelayedexpansion
for %%a in (%1) do (
fsutil file setzerodata offset=0 length=%%~za %%a
)
endlocal
Usage:
- You can pass a single filename as an argument:
zero test.txt
or a wildcard:zero *.txt
Example:
> type test.txt
abc
foo$
foo
bar
> zero test.txt
Zero data is changed
> type test.txt
>
Further Reading
- An A-Z Index of the Windows CMD command line
- A categorized list of Windows CMD commands
- fsutil - File and Volume specific commands, Hardlink management, Quota management, USN, Sparse file, Object ID and Reparse point management
- parameters - A command line argument (or parameter) is any value passed into a batch script.
Solution 2:
Not exactly a solution, but if you have CygWin installed, you just do (example for a 500000000 bytes file) :
dd if=/dev/zero of=MyFile.zero bs=1 count=500000000
This is the same method you would use at any Unix-like operating system.