This page is edited from the 1cmdfaq.txt faq-file contained in
my tscmd.zip
command line interface (CLI) collection. That zipped file has much
additional material, including a number of detached .cmd script
files. It is recommended that you also get the zipped version as a
companion.
Please see "
The Description and
the Index page" for the conditions of usage and other such
information.
41} How can I create a zero-byte file? How do I test for it?
@echo off
rem Don't destroy an existing file
if exist testfile goto _nocreate
:: Create the zero-byte file
type nul>testfile
:_nocreate
or
@echo off
if exist testfile goto _nocreate %Don't destroy an existing file%
echo off>testfile
:_nocreate
Alternatively
@echo off
copy /-y nul testfile
To see one of the small but significant differences bewtween
NT/2000/XP/.. and MS-DOS+Win../95/98/Me solutions compare the above
solution with item #42 of
tsbat.zip
In MS-DOS+Win../95/98/Me rem can used for the purpose, but not the
copy nul solution.
Another option. This time with a long name and also a file-size test
included.
@echo off & setlocal enableextensions
set testfile_="My test file"
if exist %testfile_% goto _nocreate
%Don't destroy an existing file%
copy nul %testfile_%>nul
:_nocreate
call :TestForZeroFile %testfile_% isZeroFile_
echo %testfile_% is a zero-byte file = %isZeroFile_%
endlocal & goto :EOF
::
:: ====================================
:TestForZeroFile
setlocal enableextensions
set file_=%1
for %%f in (%file_%) do set size_=%%~zf
set return_=false
if %size_% EQU 0 set return_=true
endlocal & set %2=%return_% & goto :EOF
Screen captures:
D:\TEST>cmdfaq
"My test file" is a zero-byte file = true
D:\TEST>dir | find "My"
24.12.2003 09:56 0 My test file
Or, simpler still the test could be coded as
:: ====================================
:TestForZeroFile
setlocal enableextensions
set size_=%~z1
set return_=false
if %size_% EQU 0 set return_=true
endlocal & set %2=%return_% & goto :EOF
As an unrelated aside, note the three alternatives employed in this
item of making comments, including using the percent
% signs.
Actually, that trick is just using non-existing environment variables.