Programming Field

NUL (empty file) - DOS/Command Prompt Reference

In MS-DOS and Windows ‘NUL’ is a kind of device file name, and is treated as an empty file. Reading NUL will reach to end (EOF) with 0 bytes and writing to NUL has no effect. (Writing operation will succeed.)

NUL is almost same as ‘/dev/null’ in Linux.

Details

Usage of NUL

‘Device files’ are like virtual files which can be used as normal files in file I/O. If you specify ‘NUL’ for commands as a file, you can get the effect such that ‘commands read 0-byte data’ or that ‘commands finish successfully with no output’.

The ‘NUL file’ exists in any directories. Therefore, the file ‘<any-path>\NUL’ exists if <any-path> is a valid directory, and can be opened for reading/writing. (Just like no path is specified to NUL, reading ends with 0 bytes and writing has no effect.)

* Similarly for other device files, ‘NUL’ is a reserved name by system and you cannot use NUL as a file/directory name.
* [Windows NT series] If you write ‘if exist <any-path>\NUL ...’, the command ‘...’ will be executed if ‘<any-path>’ directory exists. However if you enclose it in ‘" "’ such like ‘if exist "<any-path>\NUL" ...’, the path will be treated as non-existing file, and ‘...’ will not be executed. Therefore, checking existence for ‘<any-path>’ by using ‘<any-path>\NUL’ can only be used if ‘<any-path>’ has no space characters. (On Windows NT series ‘if exist’ itself supports directory existence checks.)

Samples

Sample 1

type NUL > null.txt

By using the effect ‘reading NUL will reach to EOF with 0 bytes’, executes Type command to create a file ‘null.txt’ with 0 bytes.

Sample 2

copy NUL null.txt

[Windows NT series/XP and later] Executes Copy command to create a file ‘null.txt’ with 0 bytes. ([MS-DOS, Windows 95/98/Me] You cannot use this command because 0-byte files cannot be copied with Copy command.)

Sample 3 (Batch file)

:CheckDrive
echo Please insert a disk to drive A and press any key when ready...
pause > NUL
if not exist A:\NUL goto CheckDrive
main.exe A:\

In the third line, by using the effect ‘writing to NUL has no effect’, suppresses ‘Press any key to continue . . .’ message which Pause prints.

In the fourth line, by using the effect ‘NUL file exists regardless of directory’, checks existence of the root directory of A drive (i.e. checks whether the disk is inserted to A drive). Even if the drive exists, it is assumed that the directory does not exist if the disk is not inserted.

* In some cases, if the disk is not inserted while executing the fourth line, system prints an error ‘No disk inserted’ and prompts choice for next action.

See also