Advertisement
tangent

Proof that Windows can in fact create a NUL file

Aug 24th, 2016
929
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <windows.h>
  3. #include <tchar.h>
  4.  
  5. int main()
  6. {
  7.     TCHAR cwd[32768];
  8.     GetCurrentDirectory(sizeof(cwd) / sizeof(TCHAR) - 1, cwd);
  9.  
  10.     // Build the path to NUL.  Flip the flag below to see it fail.
  11.     TCHAR path[sizeof(cwd)];
  12. #if 1
  13.     _stprintf(path, "\\\\?\\%s\\NUL", cwd);
  14. #else
  15.     _tcscpy(path, "NUL");
  16. #endif
  17.  
  18.     // Create the file, if it doesn't exist yet
  19.     HANDLE h = CreateFile(path, GENERIC_WRITE, 0, 0,
  20.                   CREATE_ALWAYS, 0, 0);
  21.     if (h != INVALID_HANDLE_VALUE) {
  22.         // Write our test string to the file.  If the flag above is 1
  23.         // and you try to open this file with Explorer or cmd.exe, it
  24.         // will fail, but you *can* open it with, say, Cygwin, because
  25.         // Cygwin opens files via a full path like the one we use in the
  26.         // "1" case above, bypassing the NUL path name special case code
  27.         // inside the Windows kernel.
  28.         LPTSTR s = _T("booga, booga!\n");
  29.         DWORD nWritten, nExpected = _tcslen(s) * sizeof(TCHAR);
  30.         if (WriteFile(h, s, nExpected, &nWritten, 0)) {
  31.             _tprintf("Wrote %d bytes to %s.\n", nWritten, path);
  32.         }
  33.         CloseHandle(h);
  34.     }
  35.     else {
  36.         // This shouldn't happen, even if you flip the flag above.  The
  37.         // "0" case doesn't cause an error, it just sends the written
  38.         // bytes to the bit bicket, emulating Unix's /dev/null.
  39.         LPTSTR errorText = 0;
  40.         FormatMessage(
  41.             FORMAT_MESSAGE_FROM_SYSTEM |
  42.             FORMAT_MESSAGE_ALLOCATE_BUFFER |
  43.             FORMAT_MESSAGE_IGNORE_INSERTS,  
  44.             0,
  45.             GetLastError(),
  46.             MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  47.             (LPTSTR)&errorText,
  48.             0,
  49.             0);
  50.         _tprintf("Failed to create NUL: error %s\n", errorText);
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement